Boss lesson · Unit 03
A worker pool
Fan out, fan in, chain stages, cancel, and untangle a deadlock.
What you practise
- Fan out and fan in, a pipeline of stages, cancelling with
context, reading a deadlock and fixing it
Try a question from this lesson
Pick one
You have 500 images to resize and want only 4 at a time. So 4 goroutines all receive from one channel of jobs. Two are waiting when one job is sent. What happens?
Correct answer
Exactly one of them receives the job
Why
A value sent on a channel is delivered to exactly one receiver. That makes a channel a safe work queue: several goroutines can pull from it and no job is done twice, without a lock anywhere in your code.
The ideas
Concept cards are short on purpose. In the app they appear between questions, after you have met the idea.
Concept
The shape of a worker pool
A worker pool is two channels and a handful of goroutines. Jobs go into one channel; every worker ranges over it, so the work fans out to whichever worker is free. Each worker sends what it produced to a second channel, where the results fan in.
The number of workers caps how much runs at once. Closing the jobs channel is how you tell the workers to go home.
+-> worker --+
jobs -> in +-> worker --+-> out -> results
+-> worker --+
fan out: one channel, many receivers
fan in: one channel, many sendersConcept
Fan in: who closes the results?
Counting results only works when you know how many to expect. The general way is to range over the results channel, and then someone must close it, but only after every worker has stopped sending.
No single worker knows that. So a WaitGroup counts the workers, and one extra goroutine waits for them all and then closes the channel. Here work squares numbers from in onto out.
var wg sync.WaitGroup
for range 3 {
wg.Add(1)
go func() {
defer wg.Done()
work(in, out)
}()
}
go func() {
wg.Wait() // every worker has returned
close(out) // so nobody sends again
}()
for sq := range out {
sum += sq
}Concept
Cancelling with context
A context.Context carries a stop signal through a program. ctx.Done() returns a channel that is closed when the context is cancelled, so any number of goroutines can select on it, and ctx.Err() then says why.
context.WithCancel hands you a cancel function to call. context.WithTimeout also cancels by itself after a duration. By convention ctx is the first parameter of any function that might block.
ctx, cancel := context.WithTimeout(
context.Background(), time.Millisecond)
defer cancel()
select {
case <-time.After(time.Second):
fmt.Println("finished")
case <-ctx.Done():
fmt.Println(ctx.Err())
}
// context deadline exceeded9 more exercises in the app
- 2× fill the blanks
- 3× type the answer
- 1× true or false
- 3× multiple choice
Bitpath is an iOS app in development. Join the waitlist and you get one email when it is ready to try.