Errgroup to terminate all running goroutines with child goroutine

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.

Something like this (playground)

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)
	}
}
2 Likes