Go Snippet

Goroutine + Channel Fan-Out

Difficulty: Medium

Fan-out is the canonical Go concurrency pattern: a producer pushes jobs onto a channel, a fixed pool of worker goroutines pulls and processes them in parallel, and results flow back through a results channel. This snippet shows a minimal worker pool, the close + range idiom that signals completion, and a `sync.WaitGroup` variant for fire-and-forget. Use this whenever you need parallelism with a bounded number of workers.

Code Snippets
/

Goroutine + Channel Fan-Out

Goroutine + Channel Fan-Out

Fan-out is the canonical Go concurrency pattern: a producer pushes jobs onto a channel, a fixed pool of worker goroutines pulls and processes them in parallel, and results flow back through a results channel. This snippet shows a minimal worker pool, the close + range idiom that signals completion, and a `sync.WaitGroup` variant for fire-and-forget. Use this whenever you need parallelism with a bounded number of workers.

Go
Medium
3 snippets
go-goroutines
go-channels
go-concurrency-patterns
concurrency

856 views

15

Two channels carry direction: jobs flows producer to workers, results flows workers to consumer. The worker uses for j := range jobs which exits cleanly when jobs is closed; that is what the close(jobs) after the producer loop does. A sync.WaitGroup tracks how many worker goroutines are still running so the consumer can close results only when all workers have finished. The buffered channels (make(chan int, 10)) decouple producer and consumer enough to overlap, but pick the buffer size based on actual workload, not by reflex. The whole pattern is O(jobs / workers) wall time at the cost of one goroutine per worker plus two channels.