Thread Coordination
A restaurant kitchen app has cashier threads that take orders and cook threads that prepare them. A cook with nothing to do must wait until an order arrives. A cashier must wait if the ticket rail is full, so the kitchen isn't buried. At closing time, the manager must wait until every cook has finished before printing the day's report.
None of this is about two threads corrupting data. It is about timing: one thread can't continue until
another has done something. Locks alone can't express that. This post covers the tools that can: condition
variables (and Java's wait/notify), blocking queues for producer-consumer handoffs, and latches and barriers
for "wait until N things have happened."
💡 Why this matters in an interview: coordination problems (a job scheduler, an async logger, a web crawler, a bounded queue) are graded on two things: no thread ever sleeps forever, and no thread burns CPU while waiting. Knowing which tool gives you both, and why the
whileloop matters, is most of the answer.
Why Not Just Check in a Loop?
The obvious way to wait is to keep looking. Here is a cook waiting for orders:
class TicketRail:
def __init__(self) -> None:
self._orders: list[str] = []
self._lock = threading.Lock()
def take(self) -> str:
while True:
with self._lock:
if self._orders:
return self._orders.pop(0)
# nothing yet: loop and look again
This is correct, but it is a busy wait. Each idle cook spins at 100% of a CPU core asking "anything yet?" millions of times a second, and the lock it grabs on every pass slows down the cashiers who need it to add orders.
The usual patch is to sleep between checks:
time.sleep(0.05) # check 20 times a second
Now an idle cook costs little, but an order waits up to 50 ms before anyone notices it. Shorter sleeps waste CPU; longer ones add delay. There is no good number, because the cook is guessing when to look. What it really wants is to sleep until someone tells it there is an order. That is what a condition variable does.