A condition variable is a synchronization primitive that lets one or more threads block until a condition on shared state becomes true, and lets another thread wake them when it changes that state. In concurrency and systems programming, it is always paired with a mutex that protects the shared data, and it replaces wasteful polling loops with efficient sleeping and signaling.
The condition variable itself stores no value and remembers no event. It is a queue of waiting threads, and the actual condition, called the predicate, lives in ordinary variables guarded by the mutex. This separation explains most of its rules and most of the bugs programmers make with it.
How a condition variable works with a mutex
A condition variable works by atomically releasing a mutex and suspending the calling thread in one indivisible step, then reacquiring the mutex before the thread returns from the wait. That atomicity is the whole point: if unlocking and sleeping were separate operations, a signal sent between them would be lost, a failure known as the lost wakeup problem.
The canonical pattern has three parts. The waiting thread locks the mutex, checks the predicate in a while loop, and calls wait while the predicate is false. The signaling thread locks the same mutex, modifies the shared state, and then calls signal or broadcast. Because the waiter rechecks the predicate after every wakeup, the code stays correct even when wakeups arrive for unrelated reasons.
The following table lists the core operations found in nearly every implementation, from POSIX threads to the C++ and Java standard libraries.
| Operation | What it does | Precondition |
|---|---|---|
| Wait | Releases the mutex, sleeps, reacquires the mutex on wakeup | Caller holds the mutex |
| Timed wait | Same as wait, but returns after a deadline | Caller holds the mutex |
| Signal (notify one) | Wakes at least one waiting thread, if any | Mutex usually held, not strictly required |
| Broadcast (notify all) | Wakes every thread currently waiting | Mutex usually held, not strictly required |
Spurious wakeups and the predicate loop
A spurious wakeup is a return from wait that no signal caused, and the POSIX standard and the C++ standard both explicitly permit it. Implementations allow spurious wakeups because forbidding them would make the primitive slower on multiprocessor systems and harder to build on top of kernel facilities such as Linux futexes.
Even without spurious wakeups, a woken thread cannot assume the condition still holds. Between the signal and the moment the waiter reacquires the mutex, another thread may consume the state, for example by taking the single item that was just placed in a queue. For this reason the rule is absolute: always wait inside a loop that rechecks the predicate. C++ offers an overload of wait that accepts a predicate and runs this loop internally.
Wakeup semantics differ between models, and the difference determines how much the waiter can trust a wakeup, as the table shows.
| Semantics | Who runs after signal | Waiter must recheck predicate |
|---|---|---|
| Mesa semantics | Signaler continues; waiter competes for the lock later | Yes, always |
| Hoare semantics | Waiter runs immediately with the lock handed over | In theory no, in practice yes |
| Hansen variant | Signal must be the last action before leaving | Rarely needed |
Almost every modern library, including pthreads, std::condition_variable, Java monitors and Python threading.Condition, uses Mesa semantics, which is why the predicate loop is mandatory in practice.
Condition variables compared with related primitives
A condition variable differs from other primitives in the Concurrency toolbox because it is stateless and coordination-focused: it does not count, own or store anything. Neighboring primitives such as the semaphore and the mutex are often confused with it, yet they answer different questions.
| Primitive | Keeps state | Main purpose | Typical misuse |
|---|---|---|---|
| Condition variable | No, the predicate lives elsewhere | Wait until shared state changes | Waiting without a predicate loop |
| Mutex | Owner and locked flag | Mutual exclusion of a critical section | Holding it while blocking on input |
| Semaphore | Integer counter | Count available resources or permits | Using it as a lock without ownership |
| Event or latch | Set or unset flag | One-time or manual reset notification | Expecting it to protect data |
| Spinlock | Locked flag | Very short critical sections | Spinning while waiting for a slow condition |
A semaphore remembers signals that arrive before anyone waits, whereas a condition variable forgets a signal when no thread is waiting. This is not a defect; it is exactly why the predicate must be stored in shared variables and checked under the mutex rather than inferred from the signal.
Typical use in the producer-consumer pattern
The most common application of condition variables is a bounded buffer, the classic solution to the producer-consumer problem. One mutex protects the queue, and two condition variables express two separate predicates: “the queue is not empty” for consumers and “the queue is not full” for producers.
- The consumer locks the mutex and waits on
not_emptywhile the queue length is zero. - The producer locks the mutex, waits on
not_fullwhile the queue is at capacity, then pushes an item. - After pushing, the producer signals
not_empty; after popping, the consumer signalsnot_full. - Both sides release the mutex as soon as the queue operation completes.
Using one condition variable per predicate lets each signal target only threads that can make progress. A single shared condition variable also works, but then signaling one thread may wake the wrong kind of waiter, so the code must switch to broadcast to stay correct, which costs extra context switches.
The choice between signal and broadcast follows a simple decision rule.
| Situation | Recommended call | Reason |
|---|---|---|
| One item added, waiters are interchangeable | Signal | Exactly one waiter can make progress |
| Shutdown or configuration change | Broadcast | Every waiter must observe the new state |
| Waiters wait for different predicates | Broadcast or separate variables | A single signal may reach the wrong waiter |
| Several resources released at once | Broadcast or repeated signal | More than one waiter can proceed |
Common mistakes and failure modes
Most condition variable bugs are timing-dependent, so they pass tests and fail under production load. The following list covers the failures that experienced reviewers look for first.
- Using if instead of while around wait, which breaks on spurious wakeups and stolen state.
- Changing the predicate without the mutex, which creates a race condition and can lose wakeups.
- Waiting with different mutexes on the same condition variable, which is undefined behavior in POSIX.
- Signaling before updating state, so the woken thread sees the old value and sleeps again.
- Holding a second lock while waiting, which only releases one mutex and invites deadlock.
- Forgetting a timeout or shutdown flag, leaving threads blocked forever when the program exits.
Performance pitfalls also exist. A broadcast to hundreds of waiters causes a thundering herd, where every thread wakes, contends for the mutex and most go back to sleep. Signaling while holding the mutex can cause a brief wait morphing delay on some platforms, although modern implementations move the waiter directly to the mutex queue to avoid it.
The simple explanation
Imagine a waiting room at a clinic. Patients do not keep walking to the desk every minute to ask whether the doctor is free. They sit down and wait, and the receptionist calls a name when a room opens. A condition variable is that call from the receptionist.
The receptionist does not keep a list of free rooms in her voice; the real information is on the schedule board. When a patient is called, the patient still glances at the board to confirm the room is really free, because someone else may have taken it. In the same way, a waiting thread always rechecks the real data after it wakes up.
How it is used in practice
A team building a log-processing service in C++ runs eight worker threads that read lines from a shared in-memory queue with a capacity of 10,000 entries. A network thread pushes incoming lines into the queue. The first version had workers poll the queue every millisecond, which kept all eight cores busy at about 30 percent even when no traffic arrived.
The engineers replaced polling with one std::mutex and two condition variables, not_empty and not_full. Workers now call wait with a predicate that checks the queue size, and the network thread calls notify_one after each push. For shutdown, a stopping flag is set under the mutex and followed by notify_all, so every worker exits its loop cleanly.
After the change, idle CPU usage dropped to nearly zero, latency stayed below one millisecond at peak load, and the producer stopped overrunning memory because it now blocks when the buffer is full instead of growing it without limit.