0%
Concurrency and Async Programming: Threads, Locks, Event Loops, and Backpressure
Foundations
Concurrency Patterns
Asynchronous I/O
Condition Variables and Semaphores
Mutual exclusion solves only half of coordination. Threads also need to wait: a consumer waits until a queue has an item, a worker waits until there is work, a request waits until a connection is available, a main thread waits until all workers have started. This section explains why waiting is harder than it looks, why busy waiting and sleeping in a loop are poor solutions, and what properties a good waiting mechanism needs. The rest of the lesson builds on these requirements to explain condition variables, semaphores and higher level coordination tools.
Busy waiting
The most direct way to wait is to check the condition in a loop until it becomes true: while the queue is empty, do nothing. If the check reads shared state under a lock, the loop takes and releases the lock repeatedly, competing with the very thread that needs the lock to make the condition true. If it reads without a lock, it is a data race unless the state is atomic. Either way, it burns a full core while waiting, and on a machine with fewer cores than runnable threads, it steals CPU time from the thread that would change the condition, slowing everything down.
Busy waiting has legitimate uses. Spinlocks spin because the expected wait is shorter than a context switch. Low latency systems such as trading engines and packet processors dedicate cores to polling loops to avoid wakeup latency of several microseconds. These are deliberate choices with dedicated hardware. For general application code, a thread that waits should stop using the CPU until there is a reason to check again.
Sleeping and polling
The next idea is to sleep between checks: while the queue is empty, sleep for ten milliseconds. This stops burning CPU but trades it for latency and still wastes some work. An item that arrives just after a check waits almost the full sleep interval before it is noticed, so average latency rises by half the interval. Shorter intervals reduce latency but increase wasted checks. With thousands of waiting threads, the periodic wakeups alone become a significant load. Polling also needs the condition to be read safely, which still requires a lock or atomics.
Polling is acceptable when the condition depends on something that cannot signal, such as an external file system or a remote service without notifications, and when latency of the poll interval is acceptable. Within one process, where the thread that changes the condition is known and can notify, it is almost always the wrong tool.
What a good wait needs
A good waiting mechanism has four properties. It must block without using the CPU, letting the operating system run other threads. It must wake the waiter promptly when the condition may have changed. It must be safe against the lost wakeup problem: if the condition changes between the moment the waiter checks it and the moment the waiter goes to sleep, the notification must not be lost, or the waiter may sleep forever. And it must integrate with mutual exclusion, because the condition is usually a property of shared state, such as the queue being non empty, that is protected by a lock.
The lost wakeup is the subtle requirement. Imagine a consumer checks the queue under the lock, sees it empty, releases the lock, and then calls some sleep primitive. If the producer adds an item and sends a wakeup in the gap between the release and the sleep, the wakeup arrives when no one is sleeping and is lost, and the consumer then sleeps despite an item being available. Any correct waiting mechanism must make releasing the lock and going to sleep one atomic step with respect to notifications.
The family of answers
Different primitives satisfy these requirements in different ways. A condition variable is paired with a mutex and provides wait, which atomically releases the mutex and sleeps, and signal and broadcast, which wake waiters. A semaphore holds a count of permits and blocks a thread that tries to take a permit when the count is zero. Higher level tools, such as blocking queues, latches, barriers and futures, package common waiting patterns so that application code rarely needs the raw primitives. Understanding the raw primitives still matters, because the higher level tools are built from them and inherit their behavior, and because reviewing or debugging concurrent code often requires reasoning at that level.
Higher level languages often hide these choices entirely. A Go channel receive blocks until a value is sent; a Java BlockingQueue take blocks until an item is available; a Python asyncio Event wait suspends a coroutine until another coroutine sets it. Each of these is, underneath, a lock plus a waiting mechanism that solves the lost wakeup correctly. The sections that follow show how.
Waiting with a deadline
Real systems rarely want to wait forever. A request handler waiting for a connection from a pool should give up when the request deadline passes, and a shutdown routine waiting for workers should stop waiting after a grace period. Every waiting primitive therefore comes in a timed form: wait for at most some duration, or until some absolute time, and report whether the condition became true or the time ran out. Using absolute deadlines rather than relative timeouts is preferable when a wait may be retried, because a loop that restarts a ten second timeout on each spurious wakeup can wait far longer than ten seconds in total. Monotonic clocks should be used for deadlines, so that adjusting the wall clock does not shorten or lengthen waits.
Waiting in asynchronous code
The same requirements apply when the waiter is a coroutine rather than a thread, but the mechanism changes. A coroutine that waits must not block the thread it runs on, because that thread also runs every other coroutine on the event loop. Instead, it registers a callback or a future and returns control to the loop, which resumes it when the condition is signaled. Asyncio provides Event, Condition, Semaphore and Queue with the same shapes as their threading counterparts, but each wait is an await. The lost wakeup problem disappears in a single threaded event loop, because no other coroutine can run between the check and the registration unless the coroutine awaits in between, but it reappears as soon as code awaits between checking a condition and waiting for it. Mixing the two worlds is a common source of bugs: calling a blocking threading wait inside a coroutine freezes the whole loop, and signaling an asyncio primitive from another thread is unsafe without call_soon_threadsafe. A later lesson covers event loops in depth.
Waiting and cancellation
Every wait should also be cancellable. A thread blocked forever in a wait cannot be shut down cleanly, which is why Java waits throw InterruptedException when the thread is interrupted, Go code selects on a context Done channel alongside the operation, and asyncio raises CancelledError inside an awaiting coroutine. Designing waits with cancellation and deadlines from the start makes shutdown, timeouts and error handling much simpler than retrofitting them later.
In short, choose a primitive that blocks, wakes promptly, closes the lost wakeup gap, honors deadlines and supports cancellation, and the waiting part of your design will be sound.
Busy waiting burns cores and polling adds latency. A proper wait blocks without CPU, wakes promptly, integrates with the lock that protects the condition, and closes the lost wakeup gap by releasing the lock and sleeping in one atomic step. Use timed waits with monotonic deadlines so nothing waits forever.