go
46 lines · 7 steps
A graceful worker pool in Go
A worker pool that processes jobs from a channel and shuts every goroutine down cleanly with a broadcast signal.
Explained by
highlit
1package worker
2
3import (
4 "fmt"
5 "sync"
6 "time"
7)
8
9type Pool struct {
10 done chan struct{}
11 once sync.Once
12 wg sync.WaitGroup
13}
14
15func NewPool() *Pool {
16 return &Pool{done: make(chan struct{})}
17}
18
19func (p *Pool) Spawn(id int, jobs <-chan string) {
20 p.wg.Add(1)
21 go func() {
22 defer p.wg.Done()
23 for {
24 select {
25 case <-p.done:
26 fmt.Printf("worker %d: shutting down\n", id)
27 return
28 case job, ok := <-jobs:
29 if !ok {
30 return
31 }
32 select {
33 case <-p.done:
34 return
35 case <-time.After(50 * time.Millisecond):
36 fmt.Printf("worker %d: processed %s\n", id, job)
37 }
38 }
39 }
40 }()
41}
42
43func (p *Pool) Shutdown() {
44 p.once.Do(func() { close(p.done) })
45 p.wg.Wait()
46}
01 / 01
STEP 01
‹ swipe to step through ›
Walkthrough
Space play
←→ step
click any line
Three takeaways
- 1Closing a channel broadcasts to every receiver at once, which makes it the idiomatic Go shutdown signal.
- 2A sync.Once guards close so Shutdown is safe to call repeatedly without panicking on a double close.
- 3Pairing a WaitGroup with the done channel lets shutdown both signal and block until all workers actually exit.
Related explainers
go
package streaming import ( "bufio"
Streaming NDJSON logs over HTTP in Go
http-streaming
channels
select
Advanced
10 steps
go
package api import ( "crypto/sha256"
ETag conditional requests in Gin
http-caching
etag
conditional-requests
Intermediate
6 steps
go
func (w *Watcher) resetDebounce(d time.Duration) { if !w.timer.Stop() { select { case <-w.timer.C:
Debouncing a stream of events in Go
debounce
timers
channels
Advanced
7 steps
go
package logging import ( "context"
Deduplicating log attributes in Go's slog
decorator-pattern
structured-logging
immutability
Intermediate
8 steps
rust
use std::collections::VecDeque; use std::sync::{Arc, Condvar, Mutex}; use std::time::{Duration, Instant};
Building a counting semaphore in Rust
concurrency
synchronization
condition-variable
Advanced
9 steps
go
package middleware import ( "net/http"
Per-plan export limits in Gin middleware
middleware
rate-limiting
authorization
Intermediate
7 steps
Share this explainer
Here's the card — post it anywhere.
Made with highlit — turn any snippet into a walkthrough like this in about a minute.
Explain your code
Embed this explainer
Drop the interactive walkthrough into a blog or docs. Views never cost a credit.
<iframe src="https://highlit.co/explainers/a-graceful-worker-pool-in-go-explained-go-da8b/embed?autoplay=1" width="100%" height="520" loading="lazy" style="border:0"></iframe>
Autoplay is on by default — add ?autoplay=0 to start paused.