HowtoGo
Home / Concurrency / Worker Pools
Concurrency

Worker Pools

A worker pool runs a fixed number of goroutines pulling from a shared jobs channel, capping concurrency instead of spawning one goroutine per job.

Examples

Three workers share one jobs channel. Each pulls the next available job, so work distributes itself without a scheduler.

jobs := make(chan int, 5)
results := make(chan int, 5)

var wg sync.WaitGroup
for w := 1; w <= 3; w++ {
    wg.Add(1)
    go func() {
        defer wg.Done()
        for j := range jobs {
            results <- j * j
        }
    }()
}

for i := 1; i <= 5; i++ {
    jobs <- i
}
close(jobs)

wg.Wait()
close(results)

sum := 0
for r := range results {
    sum += r
}
fmt.Println(sum)
Output
55
FunctionDescription
jobs := make(chan T, n)
jobs := make(chan int, 100)
Buffered channel workers pull jobs from
results := make(chan R, n)
results := make(chan int, 100)
Channel workers send finished results to
close(jobs)
close(jobs)
Signals no more jobs; range over jobs ends once drained
sync.WaitGroup
wg.Add(1) / wg.Wait()
Tracks running workers so the caller can wait for them
for j := range jobs
for j := range jobs { ... }
Worker loop; exits automatically when jobs is closed and empty
context.Context
ctx.Done()
Shared cancellation signal for every worker and the producer
Related: Goroutines Channels Atomic Operations