I’m sorry for the delay in writing. Last week I was under the weather.
Let’s pick up our discussion of goroutines and errors.
Last time, I talked about errgroup
, which makes it easy to run an arbitrary number of goroutines, and gather the first error (if any) that one returns.
But what if that error renders the rest of the goroutines obsolete? A very common case is that any error means that the rest of the processing becomes moot.
Fortunately, errgroup
handles this case for us quite nicely. All you need to do is create your errgroup using the WithContext
constructor function.
func WithContext
func WithContext(ctx context.Context) (*Group, context.Context)
WithContext returns a new Group and an associated Context derived from ctx.
The derived Context is canceled the first time a function passed to Go returns a non-nil error or the first time Wait returns, whichever occurs first.
Let’s see it in action, by modifying the last example:
func doManyThings(ctx context.Context) error {
g, ctx := errgroup.WithContext(ctx)
for i := range 100 {
g.Go(func() error {
return doSomething(ctx, i)
})
}
return g.Wait()
}
Now, as soon as any call to doSomething()
returns an error, the group context will be canceled, signaling to all other still-running instances, that they should abort processing.