Build a worker pool that sends its results into a channel
Implement run: start workers goroutines that process the values in jobs and deliver work(job) for each one through the returned channel. Results may arrive in any order. Requirements: at most workers calls to work run at the same time; run returns the channel at once, without waiting for anyone to read it; the channel is closed after every result has been delivered; no goroutine leaks.
func run(workers int, jobs []int, work func(int) int) <-chan int {
// your code here
}Write the implementation.
Do not add extra imports unless the task says so explicitly.
Start workers goroutines that range over one jobs channel and send work(job) into an unbuffered results channel. A feeder goroutine sends the jobs and closes jobs; another waits on a WaitGroup and closes results. run returns results at once.
- Closing the results channel from each worker or before all workers finish, which panics or drops results
- Calling
wg.Wait()insiderunbefore returning, so it deadlocks on an unbuffered results channel - Starting a goroutine per job, so more than
workerscalls toworkrun at once
- How would you return the results in the order of
jobs? - How would you stop the pool early when a
contextis cancelled?
Solution
The goroutines play three roles. The workers range over the jobs channel and write each result into the results channel. The feeder goroutine sends the jobs and closes the jobs channel, so the workers leave their range loops. The closer goroutine waits on the WaitGroup and closes the results channel: whoever knows that no worker is left must close it, not the workers themselves. run waits for nothing, otherwise a send into the unbuffered channel would block with no reader.
func run(workers int, jobs []int, work func(int) int) <-chan int {
in := make(chan int)
out := make(chan int)
var wg sync.WaitGroup
for i := 0; i < workers; i++ {
wg.Add(1)
go func() {
defer wg.Done()
for j := range in {
out <- work(j)
}
}()
}
go func() { // feeds the jobs
for _, j := range jobs {
in <- j
}
close(in)
}()
go func() { // closes results once the workers are gone
wg.Wait()
close(out)
}()
return out
}The order of results is not guaranteed: whoever finishes first writes first.