Worker Pool
Fixed pool of workers processing jobs from a shared channel with graceful shutdown.
package main
import (
"fmt"
"sync"
"time"
)
func worker(id int, jobs <-chan int, results chan<- int, wg *sync.WaitGroup) {
defer wg.Done()
for job := range jobs {
fmt.Printf("worker %d started job %d\n", id, job)
time.Sleep(200 * time.Millisecond) // simulate work
results <- job * 2
}
fmt.Printf("worker %d done\n", id)
}
func main() {
const numJobs = 10
const numWorkers = 3
jobs := make(chan int, numJobs)
results := make(chan int, numJobs)
var wg sync.WaitGroup
for i := 1; i <= numWorkers; i++ {
wg.Add(1)
go worker(i, jobs, results, &wg)
}
for j := 1; j <= numJobs; j++ {
jobs <- j
}
close(jobs) // graceful shutdown: workers drain remaining jobs
go func() {
wg.Wait()
close(results)
}()
for r := range results {
fmt.Println("result:", r)
}
}