Worker Pool Graceful Shutdown

Run a fixed worker pool over a job channel, stop accepting work on signal, and drain in-flight jobs before returning with a WaitGroup.

GoResilience

Code

snippet
package main

import (
	"fmt"
	"sync"
)

func worker(id int, jobs <-chan int, wg *sync.WaitGroup) {
	defer wg.Done()
	for job := range jobs {
		// range 在 channel 关闭且取空后结束循环
		fmt.Printf("worker-%d processing %d\n", id, job)
	}
}

func main() {
	jobs := make(chan int, 16)
	var wg sync.WaitGroup

	for id := 1; id <= 3; id++ {
		wg.Add(1)
		go worker(id, jobs, &wg)
	}

	for job := 1; job <= 9; job++ {
		jobs <- job
	}
	close(jobs) // 关闭即广播:所有 worker 依次排空退出

	wg.Wait()
	fmt.Println("all workers drained")
}

How the snippet works

Worker Pool Graceful Shutdown comes down to the functions worker and main.

Repetition is confined to for job := range jobs — the rest of the file is straight-line. The goroutine/channel pair splits producer and consumer while keeping the handoff race-free. defer inverts the usual order — register now, run at return — which is why cleanup cannot be skipped.

Using it

Signature: func worker(id int, jobs <-chan int, wg *sync.WaitGroup)

Running the file prints labeled results such as worker-, all workers drained — each operation’s effect is visible in the output.

main sequences worker; executing the file runs that flow once.

Key statements

func worker(id int, jobs <-chan int, wg *sync.WaitGroup) {
	defer wg.Done()
	for job := range jobs {
		// range 在 channel 关闭且取空后结束循环
		fmt.Printf("worker-%d processing %d\n", id, job)
	}
}
jobs := make(chan int, 16)
var wg sync.WaitGroup

Interactive Tools for This Topic

FAQ

What does Worker Pool Graceful Shutdown print when run?
Execute the whole file; each printed line is prefixed with a label like `worker-`, `all workers drained`.