// Chapter 39 example: one cancel call stops three workers. // Run with: go run exercises/39/06-cancel.go package main import ( "context" "fmt" "sync" "time" ) // worker does one step of work every 400 milliseconds, until ctx is cancelled. func worker(ctx context.Context, id int) { for step := 1; ; step++ { select { case <-ctx.Done(): fmt.Printf("worker %d: stopping (%v)\n", id, ctx.Err()) return case <-time.After(400 * time.Millisecond): fmt.Printf("worker %d: step %d\n", id, step) } } } func main() { ctx, cancel := context.WithCancel(context.Background()) defer cancel() var wg sync.WaitGroup for id := 1; id <= 3; id++ { wg.Go(func() { worker(ctx, id) }) } time.Sleep(time.Second) fmt.Println("main: cancel") cancel() wg.Wait() fmt.Println("main: every worker has stopped") }