Go · Level 3 Concurrency

Worker Pools

Build a worker pool in Go: a fixed number of goroutines read jobs from one channel and send results on another, which is closed only after every worker is done.

  • N goroutines share one jobs channel
  • results go on a second channel
  • close results after wg.Wait()

A worker pool starts N goroutines that all read jobs from one channel and send results on another. Trap: close the results channel only after every worker is done; run wg.Wait() then close(results) in a separate goroutine, while you read the results.

go func() {
    wg.Wait()       // every worker finished
    close(results)  // now readers can stop
}()

Write Process(jobs []int, workers int, work func(int) int) int: run work on every job using workers goroutines and return the sum of the results. Example: jobs [1 2 3] with 2 workers, doubling each → 12.

solution.go
Test Suites Pending
Output