Skip to content

Worker pool pattern

This pattern is commonly used to manage concurrency effectively, especially when you have a set of tasks that can be processed concurrently but want to limit the number of goroutines to prevent resource exhaustion or to control the load on a system.

Simple code - A worker simulates an expensive op

package main
import "time"
func worker(input <-chan int, result chan<- int) {
for val := range input {
time.Sleep(time.Second)
result <- val * 2
}
}
func main() {
input := make(chan int)
results := make(chan int)
for range 2 {
go worker(input, results)
}
go func() {
for i := range 5 {
input <- i
}
close(input)
}()
for range 5 {
println(<-results)
}
}