Build bounded worker pools
Build bounded worker pools
A worker pool starts a fixed number of goroutines that repeatedly receive jobs. It bounds simultaneous work instead of starting one goroutine per input. Think of two checkout clerks serving a queue: more customers need not mean more clerks. This example accepts small integers and returns sorted squares.
package main
import ( "fmt" "sort" "sync")
func squares(values []int, workers int) []int { if workers < 1 { return nil } jobs := make(chan int) results := make(chan int) var wg sync.WaitGroup for i := 0; i < workers; i++ { wg.Add(1) go func() { defer wg.Done() for n := range jobs { results <- n * n } }() } go func() { defer close(jobs) for _, n := range values { jobs <- n } }() go func() { wg.Wait(); close(results) }() out := []int{} for n := range results { out = append(out, n) } sort.Ints(out) return out}func main() { fmt.Println(squares([]int{3, 1, 2, 2}, 2))}The producer owns jobs and closes it after the last send. Workers receive until closure, then call Done. A separate coordinator waits for all workers and closes results exactly once. Main drains results while workers run; waiting before draining an unbuffered results channel would deadlock. Sorting makes output deterministic, not processing order. The function uses finite input; production jobs need cancellation and bounded input queues.
Expected output:
[1 4 4 9]Handle empty input and invalid configuration
package main
import ( "fmt" "sort" "sync")
func squares(values []int, workers int) []int { if workers < 1 { return nil } jobs := make(chan int) results := make(chan int) var wg sync.WaitGroup for i := 0; i < workers; i++ { wg.Add(1) go func() { defer wg.Done() for n := range jobs { results <- n * n } }() } go func() { defer close(jobs) for _, n := range values { jobs <- n } }() go func() { wg.Wait(); close(results) }() out := []int{} for n := range results { out = append(out, n) } sort.Ints(out) return out}func main() { fmt.Println(len(squares(nil, 2))) fmt.Println(squares([]int{1}, 0) == nil)}Zero workers cannot consume jobs; this demonstration rejects that configuration with nil. A production API should return an explicit error. Limit workers based on measured workload and downstream capacity; more workers do not guarantee faster execution.
Expected output:
0trueTry it locally
Use the pool with three workers and input [4, 0, 2]. Print sorted squares [0 4 16].
Check Your Understanding
Solidify your learning with the interactive assessment directly below this lesson.
Concept Quiz & Questions
Concurrency patterns 01: Build bounded worker pools
Check the lesson objective before moving on.
Who closes results?
Why drain while workers run?