// Chapter 38 example: a worker pool. Three workers share eight jobs, so no more // than three jobs run at once. Each job pretends to work for 100 milliseconds. // Run with: go run exercises/38/06-worker-pool.go package main import ( "fmt" "sync" "time" ) // result is what a worker sends back for one job. type result struct { job int square int worker int } // worker takes jobs until the jobs channel is closed and empty. func worker(id int, jobs <-chan int, results chan<- result) { for n := range jobs { time.Sleep(100 * time.Millisecond) // pretend this is slow work results <- result{job: n, square: n * n, worker: id} } } func main() { start := time.Now() jobs := make(chan int) results := make(chan result) // Start the workers. var wg sync.WaitGroup for id := 1; id <= 3; id++ { wg.Go(func() { worker(id, jobs, results) }) } // Send the jobs, then close the channel so the workers know there are no // more. This runs in its own goroutine, so main can read results meanwhile. go func() { for n := 1; n <= 8; n++ { jobs <- n } close(jobs) }() // Close results once every worker has finished. go func() { wg.Wait() close(results) }() total := 0 for r := range results { fmt.Printf("worker %d: %d squared is %d\n", r.worker, r.job, r.square) total = total + r.square } fmt.Println("Sum of the squares:", total) fmt.Println("Took about", time.Since(start).Round(100*time.Millisecond)) }