Worker pool with a wait group in Go

Go

Fixed number of goroutines draining a channel, with the group ensuring main waits for all of them.

jobs := make(chan Job)
var wg sync.WaitGroup

for i := 0; i < runtime.NumCPU(); i++ {
    wg.Add(1)
    go func() {
        defer wg.Done()
        for j := range jobs {
            process(j)
        }
    }()
}

for _, j := range allJobs {
    jobs <- j
}
close(jobs)
wg.Wait()

More in Systems

Random picks