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)})→7arrives from the channelgather([]func() int{job(1, 90), job(2, 30), job(3, 60)})→2,3,1arrivegather([]func() int{job(4, 20), job(4, 20), job(0, 20)})→0,4,4arrive 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.
Subscribe to take the course
The course is free. Sign in with Telegram and subscribe to the channel to open every lesson.