Condition variables & producer-consumer
Build a bounded blocking queue with a mutex and condition variables.
By Invicly Tech, , in Linux System Programming. About 11 minutes to read.
In short
A condition variable lets a thread sleep until some shared state changes, instead of spinning. It is always paired with a mutex: lock, check the condition in a while loop, and wait, which atomically unlocks and sleeps. The bounded producer-consumer queue is the classic pattern behind thread pools.
Explained simply
Sometimes a thread must wait until something happens: a job arrives, a buffer has space, a file finished loading. Checking again and again in a loop (busy waiting) wastes a whole CPU core. A condition variable lets the thread sleep and be woken when the situation may have changed.
A condition variable does not hold any data. It is only a doorbell. The real information, such as "the queue has 3 items", lives in normal variables protected by a mutex. The waiting thread checks those variables, and if the answer is "not yet", it rings off and sleeps.
The other side changes the variables while holding the mutex, then rings the bell with pthread_cond_signal (wake one sleeper) or pthread_cond_broadcast (wake all sleepers).
The classic use is a producer-consumer queue. Producers add jobs, consumers take them. If the queue is full, producers sleep. If it is empty, consumers sleep. Almost every thread pool, logger and web server is built on this pattern.
Press Play on a diagram to walk through it one step at a time.
- 1Lock the mutex
- 2While empty: pthread_cond_wait
Atomically unlocks and sleeps; relocks on wake.
- 3Take one item
- 4Signal not_full and unlock
- 5Process the item outside the lock
- Back to step 1
- Consumer to Queue (mutex): lock; count is 0; wait on not_empty1lock; count is 0; wait on not_empty
- Producer to Queue (mutex): lock; add item; count = 12lock; add item; count = 1
- Producer to Consumer: signal not_empty; unlock3signal not_empty; unlock
- Consumer to Queue (mutex): wakes holding the lock; count is 1, take item4wakes holding the lock; count is 1, take item
- Consumer to Producer: signal not_full; unlock5signal not_full; unlock
- 6process the item outside the lockConsumer to Consumer: process the item outside the lock
In depth
Why the wait must release the mutex atomically
Picture a consumer that checks "is the queue empty?", sees yes, and then goes to sleep. If a producer adds an item and signals in the tiny gap between the check and the sleep, the signal reaches nobody. The consumer then sleeps forever even though work is waiting. This is the lost wakeup problem.
pthread_cond_wait solves it by taking the mutex as an argument. The consumer checks the condition while holding the mutex, so the producer cannot change the queue in between. Then wait releases the mutex and starts sleeping as one indivisible step. When woken, it takes the mutex again before returning. So your code always sees the shared state while holding the lock, both before and after the wait.
- Consumer to Queue state: check: queue is empty1check: queue is empty
- Producer to Queue state: add an item2add an item
- Producer to Consumer: signal: nobody is waiting yet3signal: nobody is waiting yet
- 4go to sleep: misses the itemConsumer to Consumer: go to sleep: misses the item
- Consumer to Queue state: Fix: check and wait under the mutex5Fix: check and wait under the mutex
Why while and not if: spurious and stolen wakeups
When pthread_cond_wait returns, the condition might be false again, for two reasons. First, POSIX allows spurious wakeups: the wait may return even though nobody signalled, because of how futexes and signals are implemented. Second, and more common in practice, the wakeup can be stolen. A producer adds one item and signals. Before the woken consumer gets the mutex back, a different consumer that was just arriving grabs the lock and takes the item. By the time the first one runs, the queue is empty again.
The cure for both is the same: loop. while (count == 0) pthread_cond_wait(...). Treat a wakeup as a hint to look again, never as a promise. The condition in the while loop, read under the mutex, is the only truth.
- while (!ready) pthread_cond_wait(&cv, &m);
- The predicate lives in your variables, not in the condition variable
- A condition variable remembers nothing: a signal with no waiters is lost
signal or broadcast?
pthread_cond_signal wakes at least one waiting thread. Use it when any single waiter can make progress and one change helps exactly one thread, like one item added to a queue.
pthread_cond_broadcast wakes every waiter. Use it when the change may let many threads proceed (a shutdown flag, a barrier opening, a large batch of items) or when different threads wait on one condition variable for different reasons. If unsure, broadcast is always correct, because every thread re-checks its own condition; signal is an optimisation. The cost of broadcast is the thundering herd: many threads wake, fight for the mutex, and most go back to sleep.
You may signal while holding the mutex or right after unlocking. Both are correct, as long as the shared state was changed under the mutex.
Shutting a queue down cleanly
A worker blocked in pthread_cond_wait will never notice that you want to exit unless you tell it. Add a closed flag to the queue. To shut down: lock, set closed = 1, broadcast on both conditions, unlock. Consumers change their loop to while (count == 0 && !closed) wait, and after waking they return a "no more work" result when the queue is empty and closed. Producers refuse new items once closed.
Then join every worker. This drains the remaining jobs before exit instead of losing them. Avoid pthread_cancel for this: cancelling a thread inside a critical section is hard to get right, while a flag plus broadcast is simple and predictable.
- closed flag + broadcast = clean shutdown
- Consumers finish queued work, then return
- Join workers after closing the queue
Waiting with a timeout
pthread_cond_timedwait takes an absolute deadline, not a duration. By default that deadline is measured on CLOCK_REALTIME, the wall clock, so if NTP or an admin changes the time, your timeout can fire far too early or late. Create the condition variable with pthread_condattr_setclock(&attr, CLOCK_MONOTONIC) and compute the deadline from clock_gettime(CLOCK_MONOTONIC) to avoid that. glibc 2.30 and later also offer pthread_cond_clockwait, which takes the clock as an argument.
The call returns ETIMEDOUT when the deadline passes, and it reacquires the mutex in that case too. Because of spurious wakeups, keep the while loop and compute the deadline once before the loop, so repeated wakeups do not keep pushing it later.
- Deadline = now + timeout, computed once
- rc == ETIMEDOUT: give up, but you still hold the mutex
- Prefer CLOCK_MONOTONIC for timeouts
Learn it in 4 short steps
About 1h each. Track them with a timer in your plan.
- 1Wait on a condition in a while loop~1h
- 2Signal and broadcast waiting threads~1h
- 3Build a bounded producer-consumer queue~1h
- 4Explain spurious wakeups~1h
Key points
- Always re-check the condition in a while loop because wakeups can be spurious.
- Change the shared state while holding the mutex, then signal.
- pthread_cond_signal wakes one waiter; pthread_cond_broadcast wakes all of them.
- A bounded queue needs two conditions: not_empty and not_full.
Key terms
Tap a card to flip it. 0/6 known
Examples
#include <pthread.h>
#define CAP 16
static int buf[CAP], head, count;
static pthread_mutex_t m = PTHREAD_MUTEX_INITIALIZER;
static pthread_cond_t not_empty = PTHREAD_COND_INITIALIZER, not_full = PTHREAD_COND_INITIALIZER;
int get(void) {
pthread_mutex_lock(&m);
while (count == 0) pthread_cond_wait(¬_empty, &m);
int v = buf[head]; head = (head + 1) % CAP; count--;
pthread_cond_signal(¬_full);
pthread_mutex_unlock(&m);
return v;
}The consumer side; put() mirrors it, waiting on not_full and signalling not_empty.
The producer side with a shutdown flag
The explainer shows get(). Here is the matching put() plus close(). Step 1: put locks and waits on not_full while the buffer is full and the queue is still open. Step 2: if the queue was closed, it refuses the item. Step 3: otherwise it stores the item at the tail, raises count, and signals not_empty for one consumer. Step 4: close sets the flag and broadcasts on both conditions, because every waiter must wake up and notice. Consumers should loop on count == 0 && !closed and return -1 when the queue is empty and closed.
static int closed; /* protected by m, like buf, head and count */
int put(int v) {
pthread_mutex_lock(&m);
while (count == CAP && !closed) pthread_cond_wait(¬_full, &m);
if (closed) { pthread_mutex_unlock(&m); return -1; }
buf[(head + count) % CAP] = v; count++;
pthread_cond_signal(¬_empty);
pthread_mutex_unlock(&m);
return 0;
}
void close_queue(void) {
pthread_mutex_lock(&m); closed = 1;
pthread_cond_broadcast(¬_empty); pthread_cond_broadcast(¬_full);
pthread_mutex_unlock(&m);
}Wait at most 2 seconds for a result
A thread waits for a worker to set ready, but must not hang forever. Step 1: create the condition variable with a monotonic clock so time changes do not matter. Step 2: compute the absolute deadline once. Step 3: loop on the predicate, because wakeups can be spurious. Step 4: stop on ETIMEDOUT. In both cases the mutex is held after the wait, so unlock once at the end.
pthread_condattr_t ca; pthread_condattr_init(&ca);
pthread_condattr_setclock(&ca, CLOCK_MONOTONIC);
pthread_cond_init(&cv, &ca); /* done once at startup */
struct timespec dl; clock_gettime(CLOCK_MONOTONIC, &dl);
dl.tv_sec += 2; /* deadline, not a duration */
int rc = 0;
pthread_mutex_lock(&m);
while (!ready && rc != ETIMEDOUT) rc = pthread_cond_timedwait(&cv, &m, &dl);
int got = ready; /* read the predicate under the lock */
pthread_mutex_unlock(&m);
if (!got) fprintf(stderr, "timed out\n");Quick reference
- Pattern: lock; while (!cond) pthread_cond_wait(&cv, &m); use data; unlock
- Change shared state under the mutex, then signal or broadcast
- signal wakes at least one waiter; broadcast wakes all; a signal with no waiter is lost
- Bounded queue = 1 mutex + 2 condition variables: not_empty and not_full
- Shutdown: set closed under the lock, broadcast, then join the workers
- pthread_cond_timedwait takes an absolute time and returns ETIMEDOUT
- Use pthread_condattr_setclock(CLOCK_MONOTONIC) for timeouts
Common mistakes
- Using if instead of while around pthread_cond_wait.
- Signalling without changing the state under the mutex, which causes missed wakeups.
Quick quiz
Pick an answer to see if you're right and why.
Practice exercises
Try each one yourself first. Use the hint if you get stuck, then compare with the solution.
- Exercise 1easy
Make main wait until a worker thread sets ready = 1, using a mutex and a condition variable instead of a busy loop.
- Exercise 2medium
Build a bounded queue of capacity 4 with 2 producers (each puts 1000 numbers) and 3 consumers. Check that consumers together receive exactly 2000 items.
- Exercise 3hard
Write a fixed thread pool: pool_submit(fn, arg) adds a job to a queue, N workers run jobs, and pool_shutdown() finishes queued jobs, then joins all workers.
Check yourself
Answer in your head, reveal, then be honest with yourself.
Feel confident about this topic?
Frequently asked questions
- Can I use a condition variable without a mutex?
- No. pthread_cond_wait requires a locked mutex, and the shared state it waits on must be protected by that same mutex, or wakeups can be lost.
- Do spurious wakeups really happen?
- They are allowed by POSIX and rare on Linux, but stolen wakeups from other threads are common. A while loop handles both, so always use one.
- What is the difference between a condition variable and a semaphore?
- A semaphore stores a count, so a post with no waiter is remembered. A condition variable stores nothing; it only wakes threads that check a predicate you keep yourself.