I am trying to terminate all running goroutines if one fails. It is normally easy but I couldn’t make it work for goroutines that contain child goroutines. What I need from this example is that, when the iteration comes to ID:4 COUNTER:2 step, everything should fail. However, all continue until the end. I injected errgroup from the main to run but it didn’t change anything. Also moved groups inside loops but it didn’t work either.
If you want go routine cancellation then you will need to use errgroup.WithContext - then check the context within each goroutine to see if it has exited.
package main
import (
"context"
"errors"
"fmt"
"math/rand"
"time"
"golang.org/x/sync/errgroup"
)
func main() {
g, gCtx := errgroup.WithContext(context.Background())
// print random dice throws from 10 goroutines until one of them rolls a double six
for i := 0; i < 10; i++ {
id := i
g.Go(func() error {
for gCtx.Err() == nil {
a, b := rand.Intn(6)+1, rand.Intn(6)+1
fmt.Printf("Go routine %d rolls %d and %d\n", id, a, b)
if a == 6 && b == 6 {
fmt.Printf("Error from %d\n", id)
return errors.New("Double six")
}
time.Sleep(1 * time.Millisecond)
}
return nil
})
}
if err := g.Wait(); err != nil {
fmt.Printf("error %v", err)
}
}