Skip to content
Exercise · Goroutines and channels · lesson 13 of 13

Exercise: results as they are ready

Write a function func gather(jobs []func() int) chan int. It starts each job from jobs in its own goroutine and returns a channel right away, without waiting for the jobs. Each job, once it finishes, sends its result into that channel.

The jobs take different amounts of time, so the results arrive in the order the jobs finish, not in the order of jobs. In the tests, job(v, ms) is a job that waits ms milliseconds and returns v.

  • gather([]func() int{job(7, 10)}) → 7 arrives from the channel
  • gather([]func() int{job(1, 90), job(2, 30), job(3, 60)}) → 2, 3, 1 arrive
  • gather([]func() int{job(4, 20), job(4, 20), job(0, 20)}) → 0, 4, 4 arrive in any order

Constraints: exactly len(jobs) results arrive from the channel, one from each job; closing the channel is optional; for an empty jobs nothing arrives, but the function still returns a made channel, not nil; a job may wait for another job from the same jobs; two gather calls do not mix their results.

The check runs the tests with the race detector: if goroutines change a shared variable, such as a shared counter, without synchronisation, the solution fails.

Do not add extra imports unless the task says so explicitly.

gather.go — go
go · 8 lines
Ctrl+Enter run · Esc leave editor

Subscribe to take the course

The course is free. Sign in with Telegram and subscribe to the channel to open every lesson.

Sign in another way