RunGroup runs multiple blocking functions concurrently. - It returns the first error encountered. - If one function fails, it cancels the context for the others. - It waits for all functions to exit before returning.
(ctx context.Context, fns ...func(ctx context.Context) error)
| 24 | // - If one function fails, it cancels the context for the others. |
| 25 | // - It waits for all functions to exit before returning. |
| 26 | func RunGroup(ctx context.Context, fns ...func(ctx context.Context) error) error { |
| 27 | // 1. Create a derived context so we can signal cancellation to all siblings |
| 28 | ctx, cancel := context.WithCancel(ctx) |
| 29 | defer cancel() |
| 30 | |
| 31 | var wg sync.WaitGroup |
| 32 | errChan := make(chan error, len(fns)) |
| 33 | |
| 34 | for _, fn := range fns { |
| 35 | wg.Add(1) |
| 36 | // Capture fn in the loop scope |
| 37 | go func(f func(context.Context) error) { |
| 38 | defer wg.Done() |
| 39 | |
| 40 | // Pass the cancellable context to the function |
| 41 | if err := f(ctx); err != nil { |
| 42 | // Try to push the error; if channel is full, we already have an error |
| 43 | select { |
| 44 | case errChan <- err: |
| 45 | // Signal other routines to stop |
| 46 | cancel() |
| 47 | default: |
| 48 | } |
| 49 | } |
| 50 | }(fn) |
| 51 | } |
| 52 | |
| 53 | wg.Wait() |
| 54 | close(errChan) |
| 55 | |
| 56 | // Return the first error (if any) |
| 57 | return <-errChan |
| 58 | } |
no outgoing calls