Worker Pools
Fan out work across N goroutines reading from a shared jobs channel to bound concurrency.
A worker pool starts a fixed number of goroutines, functions that can run while their caller continues. They take jobs from a shared channel, which passes work between functions. This limits how many jobs run at the same time.
Start two workers, send them four jobs, and close the jobs channel so they can finish after the queue is empty.
package main
import (
"fmt"
"sync"
)
func worker(jobs <-chan int, wg *sync.WaitGroup) {
defer wg.Done()
for job := range jobs {
fmt.Println("processed", job)
}
}
func main() {
jobs := make(chan int)
var wg sync.WaitGroup
for i := 0; i < 2; i++ {
wg.Add(1)
go worker(jobs, &wg)
}
for job := 1; job <= 4; job++ {
jobs <- job
}
close(jobs)
wg.Wait()
}In production
Choose the number of workers based on the resource they use. For database work, limit workers to the number of available database connections. For processor-heavy work, start near the number of available processor cores and measure the result. A worker pool does not limit how many jobs can wait in its channel, so choose a channel capacity too.