AlgoViz

Coordination: waiting and handing over

hard 50 min

Coordination makes one thread go on only after another has done something.

Video lesson · Chapter 1 of 6

Make a prediction

0:00 / 4:20

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

  1. 1965

    Edsger Dijkstra's lecture notes Cooperating Sequential Processes (EWD123) describe semaphores, also for making one process wait for another.

  2. 1974

    Tony Hoare's Monitors: An Operating System Structuring Concept gives condition variables with signal and wait. The signalled process runs at once.

  3. 1980

    Butler Lampson and David Redell report on Mesa, where a notified process only becomes ready. Since then waits stand in loops.

  4. 2004

    Java 5 ships java.util.concurrent with CountDownLatch, CyclicBarrier, blocking queues and Condition.

  5. 2020

    C++20 adds std::latch and std::barrier. Waiting on condition variables had come with C++11.

  6. 2022

    Python 3.11 adds asyncio.TaskGroup and asyncio.Barrier: wait for all, cancel the rest at the first failure.

  7. 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.

Step 1 of 4

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.

One afternoon on the toboggan hill

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?

Start at the top. The lower you end, the more you have to write yourself, and the more can go wrong.

Why

What goes wrong without it

The usual first version shares a flag and sleeps between looks.

Python
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 there
Can you see both bugs? The last page may never be printed, and if the printer dies, layout waits forever.

The design that hurts

BookJob+ page: Page or null+ finished: bool+ layout(): sleeps+ printer(): sleeps

1/3Public fields, private loops

Each method invents its own way to wait, with its own sleep.

uses

The smell: sleep inside a while that reads a field which another thread writes.

There is no good sleep

Sleep between looksLooks in an idle hourAverage extra delayExtra delay over 300 pages
1 ms3,600,0000.5 ms0.15 s
50 ms72,00025 ms7.5 s
1 s3,600500 ms150 s
3,600 s divided by the sleep. The average delay is half a sleep, if pages become ready at random moments. Short sleeps waste the processor, long sleeps waste the reader.

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. 1

    Take the lock

    You cannot look at shared state without it.

  2. 2

    While the fact is false: wait

    wait gives the lock back and falls asleep in one step, so no signal fits in between.

  3. 3

    Act, still holding the lock

    When wait returns you hold the lock again. The fact is true now, and stays true until you let go.

The telling side

  1. 1

    Take the lock

    The same lock.

  2. 2

    Change the state

    State first. A signal without a change of state tells nobody anything.

  3. 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

The printer looks twice: before sleeping and after waking.
Python
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]))
Run it. Without the lock 1 of 6 orders sleeps forever. With notify before the state, 1 of 3. With the lock, none.
Edit and run it in your browser

Shapes

The four shapes as classes

One tool, four shapes

Condition- lock: Lock+ wait(): sleeps, lock is free+ notify()+ notifyAll()

1/5The tool

Sleep until told, with a lock around the state.

owns (dies together)

Callers see the shape. Nobody outside holds the lock or the condition.

Side by side

QuestionLatchBarrierHandoffFuture
Who is waited for?Anybody who counts downThe waiters themselvesThe other sideOne producer
Can it be used again?NoYes, in roundsYesNo
Does data move?NoNoYes, each item onceYes, read many times
Late arrivalPasses at onceBelongs to the next roundWaits for the next itemGets the value at once
If somebody diesWaits forever without timeoutRound breaks for allOther side waits: close itSet the exception
Futures have their own page. Queues with many places and many workers: producer-consumer.

Life of a barrier round

Each round ends exactly once, for everybody in it, in the same way.

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. notify wakes 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 wait where there is only one condition.
StrongOne condition per fact, notify one
How
arrived for takers, space for givers. One item can satisfy one taker.
Limit
Every change must signal the right fact. close changes both, so it wakes all on both.
Choose when
When each signal lets exactly one waiter go on.

Ready-made first

  • CountDownLatch, CyclicBarrier, Phaser
  • queue.Queue, threading.Barrier, asyncio.TaskGroup
  • std::latch, std::barrier since C++20
  • Promise.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.

Sources