Go core
Browse topics

Worker pools

Version
1.27
Review
Draft

Summary#

A worker pool runs a fixed number of goroutines that take jobs from one channel. This bounds how many jobs run at once. Closing the job channel tells the workers to finish.

Syntax#

go
for range workers {
	group.Go(func() {
		for job := range jobs {
			handle(job)
		}
	})
}

Example#

go
package main

import (
	"fmt"
	"strings"
	"sync"
)

func countWords(documents []string, workers int) []int {
	if workers < 1 {
		panic("worker count must be positive")
	}

	jobs := make(chan int) // indexes into documents
	counts := make([]int, len(documents))

	var group sync.WaitGroup
	for range workers {
		group.Go(func() {
			for i := range jobs {
				counts[i] = len(strings.Fields(documents[i]))
			}
		})
	}

	for i := range documents {
		jobs <- i
	}
	close(jobs) // no more work
	group.Wait()
	return counts
}

func main() {
	documents := []string{
		"read the manual",
		"ship it",
		"",
		"measure twice cut once",
		"done",
	}
	for i, count := range countWords(documents, 2) {
		fmt.Printf("document %d: %d words\n", i, count)
	}
}

Expected output#

Text
document 0: 3 words
document 1: 2 words
document 2: 0 words
document 3: 4 words
document 4: 1 words

Common mistakes#

Use a positive worker count and start workers before sending to an unbuffered job channel, or the first send blocks. Have the producer close jobs after the last send so workers can exit. If workers send results on a channel, receive them while jobs are still being submitted. Writing results by distinct index keeps the input order.

Version applicability#

The complete example requires Go 1.25 for WaitGroup.Go and uses integer range from Go 1.22. The pattern works from Go 1.0 with Add, Done and a counted loop.

Sources#

Attribution
DevLookup contributors
License
CC-BY-4.0