Run provides a safe way to execute Task functions asynchronously, recovering if they panic and provides all error stack aiming to facilitate fail causes discovery
(parent context.Context, tasks ...Task)
| 14 | // Run provides a safe way to execute Task functions asynchronously, recovering if they panic |
| 15 | // and provides all error stack aiming to facilitate fail causes discovery |
| 16 | func Run(parent context.Context, tasks ...Task) error { |
| 17 | ctx, cancel := context.WithCancel(parent) |
| 18 | |
| 19 | resultChannel := make(chan error, len(tasks)) |
| 20 | |
| 21 | var wg sync.WaitGroup |
| 22 | wg.Add(len(tasks)) |
| 23 | |
| 24 | for _, task := range tasks { |
| 25 | go func(fn func(context.Context) error) { |
| 26 | defer wg.Done() |
| 27 | defer safePanic(resultChannel) |
| 28 | select { |
| 29 | case <-ctx.Done(): |
| 30 | return // returning not to leak the goroutine |
| 31 | case resultChannel <- fn(ctx): |
| 32 | // Just do the job |
| 33 | } |
| 34 | }(task) |
| 35 | } |
| 36 | |
| 37 | go func() { |
| 38 | wg.Wait() |
| 39 | cancel() |
| 40 | close(resultChannel) |
| 41 | }() |
| 42 | |
| 43 | for err := range resultChannel { |
| 44 | if err != nil { |
| 45 | cancel() |
| 46 | return err |
| 47 | } |
| 48 | } |
| 49 | |
| 50 | return nil |
| 51 | } |
| 52 | |
| 53 | // Just write the error to a error channel |
| 54 | // when a goroutine of a task panics |