$linuxjunkies
>

condition variable

also: condition_variable, condvar, CV

A synchronization primitive that allows threads to wait until a specific condition is met, then be awakened when another thread signals that the condition has changed.

A condition variable is a mechanism for efficient thread communication in multi-threaded programs. Rather than repeatedly checking a condition in a loop (busy-waiting), a thread can call wait() to block until another thread calls signal() or broadcast() to notify that the condition has changed.

Condition variables must always be used together with a mutex (mutual exclusion lock) to protect the shared state they monitor. The waiting thread releases its lock while sleeping and reacquires it upon waking, preventing race conditions.

A practical example: in a producer-consumer scenario, consumer threads wait on a condition variable when a queue is empty. When a producer adds an item, it signals the condition variable, waking the consumers to process the new data. This is more efficient than constantly checking if data is available.

Related terms