
Recall first from Threads, mutexes, and deadlock
- Destroying a joinable std::thread calls std::terminate, so every thread must be joined or detached before its handle dies
- Any data race makes the whole program undefined behavior, not just the value that was raced on
- lock_guard, unique_lock, and scoped_lock release the mutex on every exit path, including exceptions
Waiting for an event without spinning
4 min readThe previous lesson protected shared data with mutexes and lock ordering. This lesson adds condition variables so threads wait for events without spinning, and names the classic bugs: deadlock, livelock, starvation, and lost wakeup.
Start from a real problem. A consumer thread must process items that a producer thread pushes into a queue. When the queue is empty, the consumer has nothing to do. The naive solution is a polling loop: lock the mutex, check the queue, unlock, repeat. That loop keeps a CPU core fully busy doing nothing useful, which on a Raspberry Pi 4 means heat and wasted power for zero work. A mutex alone cannot fix this: a mutex expresses "only one thread here at a time", not "wake me when the queue is non-empty". You need a second primitive.
A a synchronization object that threads can block on, and that other threads can signal to wake one or all blocked threads; it carries no state of its own is that primitive. In C++ it is std::condition_variable from <condition_variable>, and it always works together with a mutex and a predicate: a boolean expression over the shared state, such as "the queue is not empty". The condition variable is only the doorbell. The predicate, checked under the mutex, is the truth.
The idea comes from monitors, a structuring concept C. A. R. Hoare published in 1974. The semantics every modern system uses, including POSIX threads and C++, were shaped by the 1980 paper "Experience with Processes and Monitors in Mesa" by Butler Lampson and David Redell: a signal is a hint, not a guarantee. Between the moment a waiter is notified and the moment it actually runs again, another thread may grab the mutex and consume the item. The waiter must therefore recheck the predicate, always. That single design decision explains the entire API you are about to learn.
The safe form of waiting is wait() with a predicate:
std::unique_lock<std::mutex> lk(m);
cv.wait(lk, [] { return !q.empty(); });
// here: lk owns m, and q is guaranteed non-empty
The predicate overload is defined to mean exactly this loop:
while (!pred()) {
cv.wait(lk); // releases lk, blocks, reacquires lk on wake
}
Check the predicate while holding the mutex. If it is true, return immediately without sleeping.
Release the mutex and block as one atomic step: no notifier can slip a signal between your unlock and your sleep.
Wake up on a notification (or a spurious wakeup) and reacquire the mutex, possibly waiting behind other threads.
Recheck the predicate. If it is false, go back to step 2. If it is true, return with the lock held.
The loop is not optional politeness. A a return from a condition-variable wait that no notify caused; POSIX explicitly permits it, so correct code must tolerate it is real: the pthread_cond_wait(3) man page, which documents the POSIX layer glibc implements, states that spurious wakeups may occur. On top of that, Mesa semantics mean a genuine notification can arrive for state that is already gone by the time you relock. The predicate loop makes both cases harmless: you simply go back to sleep. Code that waits once and assumes the condition holds is broken even if it passes every test you run today.
Waking is done with notify_one(), which wakes one waiting thread, or notify_all(), which wakes all of them. If no thread is waiting, a notification has no effect and is not remembered. This is the point beginners miss: the condition variable stores nothing. All the state lives in your shared variables, protected by the mutex, and the notification only says "look again". You will see in the next section why forgetting this produces the most famous bug in this area.
The four classic concurrency bugs
4 min readConcurrency failures come in a small number of recognizable shapes. Learning to name them is half of debugging them, because each has a different symptom and a different fix.
Deadlock is the one the previous lesson covered: two or more threads each hold a lock the next one needs, and none can ever proceed. The symptom is a program that freezes with all worker threads blocked and CPU usage near zero. The fix is structural: a global lock ordering, or std::lock to acquire several mutexes together, or holding only one mutex at a time. Condition variables do not create deadlocks by themselves, but a thread that sleeps forever because of a lost wakeup looks identical from the outside, so you must tell the two apart.
Livelock looks like the opposite: threads are running, CPU usage is high, but no work completes. The classic shape is two threads that both try to take two locks, fail, politely release everything, and retry in lockstep forever. Each thread is responding to the other, and the responses cancel out. The fix is to break the symmetry: a randomized backoff between retries, or plain blocking locks with a fixed order so the retry dance never starts.
Starvation means a thread is runnable and correct but never gets the resource: the mutex is always taken by someone else, or the scheduler never picks it. On Linux, scheduling policies documented in sched(7) matter here: a busy thread under a real-time policy such as SCHED_FIFO can keep lower-priority threads from running at all. With ordinary threads, a mutex does not promise fairness, so a thread that releases and immediately retakes a lock in a tight loop can starve its peers. The fix is to hold locks briefly, avoid busy retry loops, and check priorities when real-time policies are involved.
Lost wakeup is the bug this lesson exists to prevent. A a notification delivered at a moment when the waiter is not yet blocked, so the waiter goes to sleep afterwards and never wakes although the condition is already true happens when checking the condition and going to sleep are two separate, interruptible steps:
// broken: the check and the sleep are two separate steps
if (q.empty()) { // checked without holding m
std::unique_lock<std::mutex> lk(m);
cv.wait(lk); // a notify between the lines is lost
}
The producer can push an item and call notify_one() exactly between the if and the wait. The notification finds no waiter and evaporates, because condition variables remember nothing. The consumer then sleeps although the queue is non-empty, and if that was the last item, it sleeps forever. The symptom is a frozen program with one thread blocked in a wait and work sitting ready in the queue.
Two properties together make the bug impossible, and wait(lk, pred) provides both. First, the predicate is checked while holding the same mutex the notifier must hold to change the state, so the state cannot change between your check and your decision to sleep. Second, the release of the mutex and the blocking happen atomically, so a notifier that acquires the mutex after your release is guaranteed to find you already registered as a waiter. Remove either property and the gap reopens.
A bounded producer-consumer buffer
3 min readNow build the pattern the lab asks for: a queue with a fixed capacity, two producers, one consumer. The buffer has two distinct waiting conditions. A producer must wait while the buffer is full; a consumer must wait while it is empty. Give each condition its own condition variable, not_full and not_empty, both paired with the same mutex:
#include <condition_variable>
#include <cstdio>
#include <mutex>
#include <queue>
#include <thread>
std::mutex m;
std::condition_variable not_full, not_empty;
std::queue<int> q;
constexpr std::size_t CAP = 4;
void producer(int id) {
for (int i = 0; i < 1000; ++i) {
std::unique_lock<std::mutex> lk(m);
not_full.wait(lk, [] { return q.size() < CAP; });
q.push(id * 1000 + i);
not_empty.notify_one();
}
}
void consumer() {
long sum = 0;
for (int i = 0; i < 2000; ++i) {
std::unique_lock<std::mutex> lk(m);
not_empty.wait(lk, [] { return !q.empty(); });
sum += q.front();
q.pop();
not_full.notify_one();
}
std::printf("sum = %ld\n", sum);
}
int main() {
std::thread p1(producer, 1), p2(producer, 2), c(consumer);
p1.join(); p2.join(); c.join();
}
Build and run it on Ubuntu 24.04:
g++ -Wall -Wextra -std=c++20 -pthread buffer.cpp -o buffer
./buffer
The program prints sum = 3999000 on every run: the total is fixed by arithmetic (each producer contributes its id times 1000 per item plus the values 0 to 999), not by scheduling. We ran it three times on Ubuntu 24.04 and got sum = 3999000 each time, and once more built with -fsanitize=thread with no report. What scheduling does change is the interleaving, and the buffer never exceeds four items because the only path to push passes the q.size() < CAP predicate under the mutex.
Three decisions in this code carry the correctness. First, every wait uses the predicate overload, so spurious wakeups and stolen items are handled by the loop. Second, notify_one is sufficient because each state change enables exactly one waiter of the other kind: one pushed item enables one consumer, one freed slot enables one producer. Third, the two kinds of waiters sit on two different condition variables. If you merge them onto one condition variable and keep notify_one, a pushed item might wake a producer (which rechecks, sees the buffer still full, and sleeps again) while the consumer that could have made progress never wakes. With mixed waiters on one condition variable you must use notify_all, which wakes everyone and wastes context switches; two condition variables are the cleaner design.
One honest limitation: this program ends because every thread knows its exact item count. A real service needs a shutdown flag checked inside the predicates, plus notify_all so every waiter rechecks and exits; a notify_one at shutdown can leave the other waiters asleep forever. The later lesson on jthread and cooperative cancellation builds that machinery properly.
Going deeperunique_lock lock strategies: defer_lock, try_to_lock, adopt_lock
wait() demands a std::unique_lock, not a std::lock_guard, because it must call unlock() and lock() on the lock object as it sleeps and wakes; lock_guard exposes neither. unique_lock also accepts three tag arguments that control how it acquires the mutex:
std::unique_lock<std::mutex> l1(m1, std::defer_lock);
std::unique_lock<std::mutex> l2(m2, std::defer_lock);
std::lock(l1, l2); // acquire both without deadlock
std::unique_lock<std::mutex> t(m, std::try_to_lock);
if (t.owns_lock()) { /* won the mutex without blocking */ }
m.lock();
std::unique_lock<std::mutex> a(m, std::adopt_lock);
cv.wait(a, pred); // a already owns m, so wait is legal
std::defer_lock constructs the wrapper without locking; you lock later, which is exactly what std::lock needs to take two mutexes in a deadlock-free way (the previous lesson's lock-ordering problem, solved by the library). std::try_to_lock attempts the lock once and never blocks; owns_lock() tells you whether it worked, which is the building block for backoff strategies against livelock. std::adopt_lock assumes the mutex is already locked by this thread and just takes over ownership so RAII will unlock it. For condition variables the rule is simple: however you got there (default construction, defer_lock plus lock(), or adopt_lock), the unique_lock must own the mutex at the moment you call wait(), or the behavior is undefined.
Both notifying under the mutex and notifying after unlocking are correct: the predicate loop covers the gap either way. Notifying while still holding the lock is easier to reason about, so use it until a profiler shows that waking a thread which immediately blocks on the mutex is a real cost; then notify after unlocking.
Under the hood: futex and the atomic sleep
2 min readWhere does the "atomic unlock and sleep" actually come from? On Ubuntu 24.04, libstdc++ implements std::condition_variable on top of pthread_cond_t from glibc 2.39, and glibc builds POSIX condition variables on the fast userspace mutex: a 32-bit word in user memory that threads manipulate directly, entering the kernel only to block or wake documented in futex(2). The name says the design goal: in the uncontended case, no system call happens at all; a thread checks and updates the word with ordinary atomic instructions in userspace.
When a thread must block, the library uses the futex wait operation, and its contract is the crucial detail: the kernel compares the futex word against an expected value and puts the caller to sleep only if they match, and that comparison plus sleep is atomic with respect to wakers. If a notifier changed the word first, the comparison fails and the call returns immediately instead of sleeping. This is the kernel-level version of the same idea you apply at the top level: never let a state change slip between the check and the sleep. The library layers its own waiter bookkeeping on top, publishing a waiter's presence before the mutex becomes available again, so any notifier that then takes the mutex, changes the predicate, and signals will find someone to wake.
Waking maps to the futex wake operation, which takes a count: wake one waiter for notify_one, wake all for notify_all. The pthread_cond_signal(3) man page says signal unblocks at least one waiting thread, and POSIX allows an implementation to unblock more, another reason the predicate loop is mandatory rather than defensive. The cost picture is worth remembering on a small board: an uncontended notify with no waiters is cheap userspace work, but every real block and wake costs a system call and a context switch. Notify only when the state actually changed, wake only as many threads as can make progress, and let the predicate loop absorb the rest.
You now have the two halves of thread coordination: mutexes protect shared state, condition variables announce changes to it. The next lesson, "Futures, promises, and async tasks", packages the most common special case, delivering a single result or exception from one thread to another, so you do not have to hand-roll a mutex, a flag, and a condition variable every time one thread just needs an answer from another.
Key takeaways
- A condition variable stores no state: the predicate under the mutex is the state, and a notify with no waiter has no effect.
- wait(lock, pred) atomically releases the mutex and sleeps, then rechecks the predicate after every wakeup, so spurious wakeups are harmless.
- On Linux, glibc condition variables (which libstdc++ uses) block with the futex system call, whose compare-and-sleep step is atomic in the kernel.
- notify_one can stall a program when different kinds of waiters share one condition variable; use two condition variables or notify_all.
Reflect
- Explain to a colleague, in two sentences: implement a bounded producer-consumer buffer with a mutex and two condition variables
- Which objective are you least sure about? Re-read that section, then do its exercise in the practice pack.
- What surprised you when you ran the commands yourself?
On a real board
Repeat the key commands on your Raspberry Pi or lab board over SSH or the serial console. Note anything that behaves differently from your PC, such as missing tools, a BusyBox shell or a read-only filesystem.
References and further reading
- Man pagepthread_cond_wait(3): waiting on a condition variable
- Man pagepthread_cond_signal(3): signalling a condition variable
- Man pagefutex(2): fast user-space locking
- Man pagesched(7): scheduling APIs and policies
Official documentation first. Links checked when the lesson was published.