A condition variable is a synchronization primitive that allows threads to suspend execution until a condition involving shared state may have become true. It is normally used together with a mutex: the mutex protects the shared state, while the condition variable provides a way to wait for changes without repeatedly checking that state. Waiting atomically releases the mutex and begins waiting; before the wait operation returns normally, the thread reacquires the mutex. A notification is not proof that the condition holds, so the thread must check the condition again.
Purpose and basic model
In concurrent computing, mutual exclusion alone is often insufficient. A thread may acquire a lock safely but discover that it cannot yet proceed: a queue is empty, a buffer is full, or an operation is still in progress.
Continuously checking for a change wastes processing time. Sleeping while retaining the mutex can prevent another thread from making the required change. A condition variable addresses both problems by coordinating release of the mutex with entry into a waiting state.
Three elements form the usual programming model:
- Shared state, such as a queue and a shutdown flag.
- A mutex, protecting access to that state.
- A predicate, a Boolean expression over the state that determines whether a thread may proceed.
For example, a consumer might wait for the predicate “the queue is not empty, or shutdown has been requested.”
The condition variable does not normally store or evaluate this predicate. Its name may suggest a condition, but the condition itself belongs to the program’s data and logic. One condition variable can support several predicates, although separate variables can make notification more selective.
Fundamental operations
Interfaces differ, but most provide the following operations.
| Operation | Meaning |
|---|---|
| Wait | Release the associated mutex and suspend; reacquire the mutex before returning normally. |
| Notify one, or signal | Unblock a waiting thread, subject to the interface’s precise guarantees. |
| Notify all, or broadcast | Unblock all threads currently waiting on the condition variable. |
| Timed wait | Wait until notified, a deadline or timeout is reached, or another permitted return condition occurs. |
Here, signal means a condition-variable notification, not an operating-system signal.
A notification generally makes a thread eligible to run; it does not guarantee immediate execution. Under the semantics used by most contemporary interfaces, the awakened thread must still acquire the mutex and may compete with other threads to do so.
Atomic release and waiting
The essential guarantee of waiting is that releasing the mutex and entering the wait are coordinated atomically with respect to the relevant synchronization operations.
Without this guarantee, the following sequence would be possible:
- A consumer observes an empty queue.
- It releases the mutex.
- A producer adds an item and sends a notification.
- The consumer begins sleeping after the notification has passed.
The consumer could then remain asleep despite an available item. A correctly used condition variable closes this gap: a state-changing thread that acquires the mutex after the waiter releases it cannot slip its notification between that release and the waiter’s registration in the way described.
This is an atomicity guarantee of the synchronization protocol, not necessarily a single hardware atomic instruction.
Waiting in a loop
The standard waiting pattern is:
lock(mutex)
while not predicate(shared_state):
wait(condition, mutex)
perform_operation_on_shared_state()
unlock(mutex)
The loop is essential for two separate reasons.
First, many interfaces permit a spurious wakeup: a wait may return without a corresponding notification that the application can identify.
Second, even a genuine notification does not reserve the desired state for a particular waiter. For example, a producer may add one item and awaken a consumer, but another consumer may acquire the mutex first and remove that item. The awakened consumer must then wait again.
Replacing while with if therefore makes the code incorrect under the usual semantics, even on an implementation that never produces spurious wakeups.
Some libraries offer a predicate-taking wait operation. Conceptually, it performs this loop internally; it does not eliminate the requirement to protect and recheck the predicate.
Example: a bounded producer–consumer queue
A bounded queue illustrates why one mutex may be paired with multiple condition variables. Producers wait for free capacity, and consumers wait for available items.
The following pseudocode assumes a positive capacity, no shutdown mechanism, and operations that complete without exceptions:
shared:
queue
capacity
mutex
not_empty
not_full
put(item):
lock(mutex)
while queue.size == capacity:
wait(not_full, mutex)
queue.push(item)
notify_one(not_empty)
unlock(mutex)
take():
lock(mutex)
while queue.is_empty():
wait(not_empty, mutex)
item = queue.pop()
notify_one(not_full)
unlock(mutex)
return item
The mutex protects both the queue and the predicates derived from it. Each wait releases that same mutex, allowing another thread to change the state.
Two condition variables distinguish the reasons for waiting. With a single condition variable and one-thread notifications, a notification could select a thread whose predicate remains false rather than a thread that could make progress. Broadcasting can address that selection problem but may create unnecessary wakeups.
A shutdown protocol adds another state transition. For example, consumers might wait while the queue is empty and the queue remains open. Closing the queue would normally notify all affected waiters so that each can observe the new state.
Notifications and persistent state
A condition variable is not a queue of remembered notifications. If no thread is waiting, a notification generally has no lasting effect.
This does not imply that a thread must begin waiting before useful work arrives. Properly written code checks persistent shared state first. If a producer adds an item before a consumer starts, the consumer sees a nonempty queue and does not wait.
A lost wakeup occurs when the synchronization protocol allows a thread to miss a relevant change and sleep when it should not. Common causes include:
- Checking a predicate outside its required lock.
- Modifying predicate state without the required synchronization.
- Separating lock release from the wait operation.
- Treating notifications as stored event records.
In the conventional design, predicate checks and predicate-changing updates use the same mutex. Some more specialized designs combine condition variables with atomics, but these require a separate correctness argument; making a flag atomic alone does not close every check-to-wait gap.
Notification inside or outside the lock
Whether notification must occur while holding the lock depends on the interface. Some interfaces require ownership of the associated lock; others permit notification after unlocking.
Where both are permitted, either placement can be correct if the predicate update is properly synchronized and object lifetime is safe. Notifying after unlocking may reduce immediate lock contention, but it is not a universal optimization. Correctness depends on the state protocol, not on notification placement alone.
Relationship to other synchronization mechanisms
Mutexes and monitors
A mutex controls entry to a critical section. A condition variable controls waiting for a state-dependent reason. They solve complementary problems: the condition variable does not itself provide mutual exclusion.
Condition variables are closely associated with the monitor, an abstraction that combines protected state, mutually exclusive operations, and condition waiting. Some languages expose condition variables through monitor-like objects rather than as independently allocated primitives.
Semaphores
A semaphore maintains a count. Releasing a semaphore can leave a permit available for a later acquisition even if no thread is currently waiting.
A condition variable normally has no corresponding permit count. Availability must be represented in shared state, and awakened threads must re-evaluate it. Either mechanism can implement producer–consumer coordination, but their invariants and notification behavior differ.
Busy waiting and spinlocks
A spinlock waits by repeatedly attempting to acquire a lock. Condition variables generally permit blocked threads to stop consuming processor time while they wait for application state to change.
Implementations may still use brief spinning internally. The defining distinction is the condition-variable interface and its state-waiting semantics, not a guarantee that every wait immediately enters the operating-system kernel.
Signaling semantics and historical development
Condition variables developed alongside monitor-based approaches to concurrency in the 1970s. C. A. R. Hoare’s 1974 monitor formulation is associated with Hoare-style signaling: signaling transfers execution within the monitor to a waiting thread, while the signaling thread is suspended. This permits stronger reasoning about the condition at the point the waiter resumes.
Mesa-style signaling, associated with the Mesa programming environment, allows the signaling thread to continue. The awakened thread executes later, after it can reacquire the monitor lock. The relevant condition may have changed by then.
Most widely used modern condition-variable interfaces follow the Mesa-style model in this respect. Consequently, notification is best understood as an indication to recheck state, not a guarantee that the predicate remains true.
Interfaces and implementation
Condition variables appear in many APIs:
- POSIX threads provide
pthread_cond_wait,pthread_cond_timedwait,pthread_cond_signal, andpthread_cond_broadcast. - C++ provides
std::condition_variableandstd::condition_variable_any. - Java exposes monitor waiting through
Object.wait,notify, andnotifyAll, and explicit condition objects throughjava.util.concurrent.locks.Condition. - Python provides
threading.Condition. - Windows provides condition-variable operations used with critical sections or slim reader/writer locks.
The interfaces differ in lock requirements, interruption and cancellation behavior, timeout clocks, and guarantees concerning wakeup selection.
Implementations often combine user-space bookkeeping with blocking facilities supplied by an operating system. On Linux, such implementations commonly use futex operations. Internal counters, waiter queues, and sequencing protocols coordinate notifications and blocking without exposing those details to application code.
Correctness and limitations
Memory visibility
A notification is not a substitute for synchronization of shared data. In the conventional mutex-based pattern, memory visibility follows from the lock operations and the language’s memory model. After reacquiring the mutex, the waiting thread can inspect appropriately synchronized updates.
Unsynchronized state accesses can create a race condition or data race even when notifications appear to occur in the intended order.
Timeouts
A timeout does not prove that the predicate is false when the thread regains the mutex. State changes and timeout expiration can occur close together, so the predicate must still be checked under the lock.
Repeated relative-duration waits can also exceed an intended overall limit if every wakeup restarts the full duration. An absolute deadline avoids that particular extension. Clock selection matters because wall-clock adjustments and elapsed-time measurement have different behavior.
Liveness and efficiency
Condition variables generally do not guarantee fair selection of waiters or bounded waiting. A correct predicate loop establishes when an operation may proceed safely, but does not by itself guarantee that every thread eventually proceeds.
Broadcasting can create a thundering herd: many threads awaken, contend for one mutex, and mostly return to sleep. Conversely, notifying too few waiters can leave usable work unprocessed. Notification strategy must match how state transitions enable progress.
Condition variables also do not prevent deadlock. Although waiting releases the associated mutex, the thread may retain other locks needed by the thread that would satisfy its predicate.
Finally, lifetime and shutdown require explicit coordination. A condition variable and its protected state must remain valid while threads can access or wait on them. Destroying synchronization objects or abandoning waiters without a complete shutdown protocol can leave invalid accesses or permanently blocked threads.