Senior
How to avoid waiting for all goroutines to finish when the first error occurs in ErrGroup?
sobes.tech AI
Answer from AI
In the standard errgroup package, when the first goroutine error occurs, ErrGroup does not interrupt the other goroutines — it waits for all to complete.
To avoid waiting for all goroutines to finish upon the first error, you can use a context with cancellation (context.WithCancel). When an error occurs, call cancel(), and the other goroutines should listen to the context and terminate themselves.
Example:
import (
"context"
"golang.org/x/sync/errgroup"
)
func runTasks(ctx context.Context) error {
ctx, cancel := context.WithCancel(ctx)
defer cancel()
g, ctx := errgroup.WithContext(ctx)
g.Go(func() error {
// example task
if err := doSomething(ctx); err != nil {
cancel() // cancel others
return err
}
return nil
})
g.Go(func() error {
// another task
return doAnotherThing(ctx)
})
return g.Wait()
}
An important point — inside goroutines, you need to periodically check ctx.Done() to terminate correctly when canceled.