SoFunction
Updated on 2025-03-01

Detailed explanation of the usage of ErrGroup, the Go language extension primitive

Overview

In addition to the synchronization primitives provided in the standard library,GoLanguage is still in the sub-repositorysync4 types of extended primitives are provided:

  • golang/sync/
  • golang/sync/
  • golang/sync/
  • golang/sync/

ingolang/sync/existGo1.9ported to the standard library.

Next introductionGoThree synchronization primitives provided by the language in the extension package—golang/sync/

ErrGroup

golang/sync/For us in a groupGoroutineSynchronization, error propagation and context cancellation functions are provided in this way, and we can use this method to obtain web page data in parallel:

var g 
var urls = []string{
    "",
    ""
}
for i := range urls {
    url := urls[i]
    (func() error {
        resp, err := (url)
        if err == nil {
            ()
        }
        return err
    })
}
if err := (); err == nil {
    ("Successfully fetched all URLs.")
}

golang/sync/Methods can create aGoroutineand execute the passed function in it, andgolang/sync/Will wait for everythingGoroutineReturn, different return results of this method have different meanings:

  • If an error is returned - this groupGoroutineReturn at least one error
  • If null value is returned - allGoroutineAll executed successfully

Structure

golang/sync/The structure has3A more important part

  • cancel——CreateThe cancel function returned when theGoroutineSynchronous cancel signal between
  • wg——For waiting for a groupGoroutineSynchronous primitives for completing subtasks
  • errOnce—— Used to ensure that only one is receivedSubtaskReturned error
type Group struct {
    cancel func()
    wg 
    errOnce 
    err     error
}

These fields together formgolang/sync/Structure and provide me withsynchronousError propagationand context cancellation.

interface

We can passgolang/sync/The constructor is innovativegolang/sync/Structure:

func WithContext(ctx ) (*Group, ) {
    ctx, cancel := (ctx)
    return &Group{cancel: cancel}, ctx
}

Running new parallel subtasks requires usegolang/sync/Method, the execution process of this method is as follows:

  • CallAdd pending tasks
  • Create a new oneGoroutineAnd run subtasks
  • Call it in time when an error is returnedcancelAnderrAssignment, only the error returned at the earliest will be perceived by the upstream, and subsequent errors will be discarded.
func (g *Group) Go(){
    (1)
    go func() {
        defer ()
        if err := f(); err := nil {
            (func () {
                 = err
                if  != nil {
                    ()
                }
            })
        }
    }()
}
func (g *Group) Wait() error {
    ()
    if  != nil {
        ()
    }
    return 
}

Another one for waitinggolang/sync/The method is just called, cancel when all subtasks are completed and return possible errors.

summary

golang/sync/The implementation does not involve the underlying and running packagesAPI, it just encapsulates basic synchronous semantics to provide more complex functionality. We need to pay attention to two issues when using it:

  • golang/sync/After an error occurs or the wait is completed, it will be calledofcancelMethod synchronous cancel signal
  • Only the first error will be returned, and the remaining errors will be discarded directly

This is the end of this article about the detailed explanation of the usage of ErrGroup, the Go language extension primitive. For more related Go ErrGroup content, please search for my previous articles or continue browsing the related articles below. I hope everyone will support me in the future!