Boss lesson · Unit 08
A task runner
A whole concurrent program: a pool of workers, errors collected, results in order.
What you practise
- One program from an empty file: tasks as structs, a pool of workers fed by a channel, errors collected, results reported in order. What to learn next
Try a question from this lesson
Pick one
You have 8 tasks that each take a second. One worker does them in 8 seconds. With 4 workers taking tasks from one shared queue, about how long does it take?
Correct answer
2 seconds
Why
Four workers run four tasks at a time, so 8 tasks need two rounds of a second each. A fixed set of workers fed from one queue is called a worker pool, and it is what you build in this lesson.
The ideas
Concept cards are short on purpose. In the app they appear between questions, after you have met the idea.
Concept
The plan
A Task is a struct: an ID and a name. A Result holds the task's ID, its output and its error.
Tasks go into one channel. A few workers, all running the same function, take tasks out and send results into a second channel.
main collects one result per task, sorts them by ID and prints the report.
+--> worker 1 --+
tasks --> jobs --> worker 2 --> results
+--> worker 3 --+
|
v
sort by ID, reportConcept
The runner
Here is the heart of the program. Both channels get a buffer big enough for every task, so no send ever has to wait.
Start the workers, hand out the tasks, close the queue, then receive exactly one result per task. for range tasks just counts: once round for each task.
After that: sort by ID, and report.
in := make(chan Task, len(tasks))
out := make(chan Result, len(tasks))
for w := 0; w < 3; w++ {
go work(in, out) // three workers
}
for _, t := range tasks {
in <- t // hand out the work
}
close(in) // no more tasks
res := []Result{}
for range tasks {
res = append(res, <-out)
}10 more exercises in the app
- 4× type the answer
- 1× fill the blanks
- 3× multiple choice
- 1× order the lines
- 1× true or false
Bitpath is an iOS app in development. Join the waitlist and you get one email when it is ready to try.