Coordination: waiting and handing over
hard 50 minCoordination makes one thread go on only after another has done something.
Video lesson · Chapter 1 of 6
Make a prediction
Coordination: waiting and handing over
1:03Reel
Theory
Read or listen first. About 2 min.
What it is
Coordination is the part of concurrent design that decides *when* a thread may go on. The thread waits for something that another thread does: a fact becomes true, some work ends, a group is complete, or an item arrives.
The basic tool is the condition variable: a place to sleep, tied to a lock. Latches, barriers, handoffs, queues and futures are small classes around it, each made for one kind of waiting.
Why it exists
Programs are split into threads that depend on each other. A printer needs pages, a server may not answer before its caches are loaded, a chapter may not be bound before all its pages exist.
Looking again and again wastes the processor or comes late. Signals without state get lost. And a wait without an end turns one dead thread into a program that stands still and says nothing.
A short history
1965
Edsger Dijkstra's lecture notes Cooperating Sequential Processes (EWD123) describe semaphores, also for making one process wait for another.
1974
Tony Hoare's Monitors: An Operating System Structuring Concept gives condition variables with signal and wait. The signalled process runs at once.
1980
Butler Lampson and David Redell report on Mesa, where a notified process only becomes ready. Since then waits stand in loops.
2004
Java 5 ships java.util.concurrent with CountDownLatch, CyclicBarrier, blocking queues and Condition.
2020
C++20 adds std::latch and std::barrier. Waiting on condition variables had come with C++11.
2022
Python 3.11 adds asyncio.TaskGroup and asyncio.Barrier: wait for all, cancel the rest at the first failure.
2025
Go 1.25 adds WaitGroup.Go, which counts and starts in one call, so the two can no longer be put in the wrong order.
Words to know
- Predicate
- The fact a thread waits for, as a question about state that answers true or false.
- Condition variable
- A place to sleep. Waiting gives the lock back, waking takes it again.
- Spurious wake-up
- A wait that returns although nobody signalled. Allowed in Java and C++.
- Lost wake-up
- A signal sent before the waiter slept. Nobody remembers it.
- Stampede
- Many sleepers wake for a change that helps one of them.
- Latch
- Counts events down to zero and then stays open.
- Barrier
- A fixed number of threads wait until all have arrived, in rounds.
- Round, generation
- One use of a barrier, from the first arrival to the release.
- Handoff
- Passing an item from thread to thread, here through one place.
- Barging
- A newcomer takes what was meant for a sleeper.
- Cooperative cancellation
- A stop is a request. The job leaves by itself at the next check.
- Structured concurrency
- Threads started in a block end before the block does.
The solution, twice
Reach the regular design first. Then go where a FAANG interviewer digs.
How it works
Step through the idea, or press Play.
Lock. Look at the state
Understand it
Start here
Do not keep looking. Be told.
A printer thread needs the next page of a photo book. The page is not ready. What should the thread do? It can look again and again, which burns a processor. It can sleep a little and look, which is late every time. Or it can say: wake me when there is something to look at. This page is about the third answer, and about the four shapes it takes.
Four ways to wait: for a fact, for work to end, for each other, for a thing.
Four shapes of waiting
A fact becomes true
Condition variable. "The queue is not empty." "The state is READY." The most general one: the other three are built from it.
Work comes to an end
Latch, join, wait group. "All five checks are done." One-way: it opens once.
Everybody is here
Barrier. "All four workers finished phase 2." The waiters are also the ones waited for. It can repeat.
Something is handed over
Handoff, queue, future. An item or a result moves from one thread to another, and waiting is built in.
Which shape is it?
Why
What goes wrong without it
The usual first version shares a flag and sleeps between looks.
import timeclass BookJob: def __init__(self): self.page = None self.finished = False def printer(self): while not self.finished: if self.page is None: time.sleep(0.05) # how long is right? continue print("printing", self.page) self.page = None def layout(self, pages): for page in pages: while self.page is not None: time.sleep(0.05) self.page = page self.finished = True # the last page may still lie thereThe design that hurts
1/3Public fields, private loops
Each method invents its own way to wait, with its own sleep.
uses
sleep inside a while that reads a field which another thread writes.There is no good sleep
| Sleep between looks | Looks in an idle hour | Average extra delay | Extra delay over 300 pages |
|---|---|---|---|
| 1 ms | 3,600,000 | 0.5 ms | 0.15 s |
| 50 ms | 72,000 | 25 ms | 7.5 s |
| 1 s | 3,600 | 500 ms | 150 s |
The tool
A condition variable in three parts
A monitor explains locks with conditions in full. Here is what coordination needs. There is state (is there a page?), there is a lock that protects it, and there is a condition: a place to sleep until somebody changes the state.
The waiting side
- 1
Take the lock
You cannot look at shared state without it.
- 2
While the fact is false: wait
waitgives the lock back and falls asleep in one step, so no signal fits in between. - 3
Act, still holding the lock
When
waitreturns you hold the lock again. The fact is true now, and stays true until you let go.
The telling side
- 1
Take the lock
The same lock.
- 2
Change the state
State first. A signal without a change of state tells nobody anything.
- 3
Notify, then unlock
One waiter if one can go on, all if several could, or if they wait for different facts.
Wait and notify
from itertools import combinations# Every way to mix two threads. No real threads are needed to see the problem.def schedules(a, b): for places in combinations(range(a + b), a): yield ["W" if i in places else "S" for i in range(a + b)]def stuck(waiter, signaller): """In how many orders does the waiter sleep forever?""" bad = total = 0 for order in schedules(len(waiter), len(signaller)): s = {"ready": False, "asleep": False, "decided": False} left = {"W": list(waiter), "S": list(signaller)} for who in order: left[who].pop(0)(s) total += 1 bad += s["asleep"] return bad, totaldef look(s): s["decided"] = not s["ready"]def sleep(s): s["asleep"] = s["decided"]def look_and_sleep(s): s["asleep"] = not s["ready"]def set_ready(s): s["ready"] = Truedef notify(s): s["asleep"] = Falsedef set_and_notify(s): set_ready(s); notify(s)print("no lock:", stuck([look, sleep], [set_ready, notify]))print("notify before state:", stuck([look_and_sleep], [notify, set_ready]))print("with the lock:", stuck([look_and_sleep], [set_and_notify]))Shapes
The four shapes as classes
One tool, four shapes
1/5The tool
Sleep until told, with a lock around the state.
owns (dies together)
Side by side
| Question | Latch | Barrier | Handoff | Future |
|---|---|---|---|---|
| Who is waited for? | Anybody who counts down | The waiters themselves | The other side | One producer |
| Can it be used again? | No | Yes, in rounds | Yes | No |
| Does data move? | No | No | Yes, each item once | Yes, read many times |
| Late arrival | Passes at once | Belongs to the next round | Waits for the next item | Gets the value at once |
| If somebody dies | Waits forever without timeout | Round breaks for all | Other side waits: close it | Set the exception |
Life of a barrier round
Choosing
notify or notifyAll?
The handoff wakes sleepers after a put. Whom?
BreaksOne condition, notify one
- How
- Givers and takers sleep on the same condition.
notifywakes any one of them. - Limit
- It may wake another giver, who looks, sees a full place, and sleeps again. The taker never hears. Everybody sleeps.
- Choose when
- Never with two kinds of waiters on one condition.
WorksOne condition, notifyAll
- How
- Everybody wakes, looks, and most sleep again.
- Limit
- With 50 sleepers one page wakes 50 threads, and 49 of them for nothing.
- Choose when
- Few waiters, or Java's built-in
waitwhere there is only one condition.
StrongOne condition per fact, notify one
- How
arrivedfor takers,spacefor givers. One item can satisfy one taker.- Limit
- Every change must signal the right fact.
closechanges both, so it wakes all on both. - Choose when
- When each signal lets exactly one waiter go on.
Ready-made first
CountDownLatch,CyclicBarrier,Phaserqueue.Queue,threading.Barrier,asyncio.TaskGroupstd::latch,std::barriersince C++20Promise.all,AbortSignal
Write it yourself only when
- The interviewer asks you to
- You need a rule the library lacks, such as close and drain
- You can test every interleaving that matters
- You can name each fact and who signals it
Summary
The whole topic in one minute.
Name the fact, store it in state behind a lock, and wait for it in a loop. Change state first, then notify, with the lock held. One condition per fact lets you wake just one.
A latch counts down once. A barrier counts arrivals in rounds, and each waiter keeps its own round object. A handoff has two facts, room and item, and closing it wakes everybody on both.
Every wait ends in one of four ways: event, deadline, close or stop. Pass deadlines down, keep the first error, stop the rest, and never return while a job is still running.
- Name the fact you wait for. Put it into state, behind a lock.
- Wait in a loop. A wake-up is a hint.
- State first, then notify, with the lock held.
- Latch: opens once. Barrier: in rounds, all or nobody. Handoff: one thing moves.
- Every wait has an end: a deadline, a close, or a stop.
- Use the library, and be able to write it.