×

go · level 3 · unit 5 · lesson 1

  1. meet it
  2. guess first
  3. your turn
  4. fix it
  5. nailed it

Tap a green word if you get lost.

meet it

A pool: a few goroutines share a long queue of jobs.

One goroutine per job is fine for ten jobs, but not for a million files or a server with limits. A worker pool starts a fixed number of goroutines, say 3. Each worker takes a job from a shared jobs channel, does it, sends the result on, and takes the next.

Once every job is queued, close the jobs channel, so each worker's range loop ends. main knows how many jobs it sent, so it receives exactly that many results, then it is done.

Workers finish in any order, so a report built from their results should be added up or sorted before it is printed. That gives the same report however the work was shared out.

package main
import "fmt"
func worker(jobs <-chan int, results chan<- int) {
	for n := range jobs {
		results <- n * n
	}
}
func main() {
	jobs := make(chan int, 5)
	results := make(chan int, 5)
	for w := 0; w < 3; w++ {
		go worker(jobs, results)
	}
	for n := 1; n <= 5; n++ {
		jobs <- n
	}
	close(jobs)
	total := 0
	for i := 0; i < 5; i++ {
		total += <-results
	}
	fmt.Println("sum of squares:", total)
}

Five jobs and three workers: the first workers to finish come back for the last two.