// Chapter 39 example: the worker pool from Chapter 38, with a time limit. When // the time is up, the sender stops sending, and each worker stops, even in the // middle of a job. // Run with: go run exercises/39/07-pool-with-context.go package main import ( "context" "fmt" "sync" "time" ) // doJob pretends to work on job n for 200 milliseconds. It gives up if ctx is // done first. func doJob(ctx context.Context, n int) (int, error) { select { case <-ctx.Done(): return 0, ctx.Err() case <-time.After(200 * time.Millisecond): return n * n, nil } } // worker takes jobs until the channel is closed, or until ctx is done. func worker(ctx context.Context, jobs <-chan int, results chan<- int) { for n := range jobs { square, err := doJob(ctx, n) if err != nil { return } results <- square } } // sendJobs sends the numbers from 1 to count, and stops early if ctx is done. // Either way, it closes jobs. func sendJobs(ctx context.Context, count int, jobs chan<- int) { defer close(jobs) for n := 1; n <= count; n++ { select { case <-ctx.Done(): return case jobs <- n: } } } func main() { ctx, cancel := context.WithTimeout(context.Background(), 500*time.Millisecond) defer cancel() jobs := make(chan int) results := make(chan int) var wg sync.WaitGroup for range 3 { wg.Go(func() { worker(ctx, jobs, results) }) } go sendJobs(ctx, 20, jobs) go func() { wg.Wait() close(results) }() done := 0 for range results { done = done + 1 } fmt.Printf("Finished %d of 20 jobs.\n", done) if ctx.Err() != nil { fmt.Println("Stopped early:", ctx.Err()) } }