What is Condition variable?
A synchronization mechanism that puts a thread to sleep until a condition holds and wakes it on a signal from another thread. The condition must be rechecked after waking.
Japanese name: 条件変数
A synchronization mechanism that puts a thread to sleep until a condition holds and wakes it on a signal from another thread. The condition must be rechecked after waking.
Japanese name: 条件変数
When a queue is empty, the thread that takes items out has to wait until data arrives. Checking over and over whether it is non-empty keeps using the CPU while doing nothing. A mutex alone cannot make a thread sleep until a condition holds. A condition variable is a mechanism that keeps a thread asleep and wakes it when another thread signals that the condition has changed.
The waiting side first takes the mutex. It then writes a loop that waits while the condition does not hold. The wait operation releases the mutex and goes to sleep in one seamless step. On waking, it retakes the mutex before returning. The signaling side takes the mutex, changes the shared data and then sends the signal. If there were a gap between releasing and sleeping, a signal arriving in that gap would be missed and the thread would sleep on.
The condition is checked in a loop, not with an if. There are three reasons. The specification allows a thread to wake without a signal. Between waking and retaking the mutex, another thread may take the data first. And with a signal that wakes everyone, only some of the woken threads can proceed. Another point is that the condition variable itself remembers nothing. A signal sent when no one is waiting is lost. The condition itself is therefore kept in the shared data, and that is what is checked.
Answer: C. Even after waking, another thread may have taken the item first or the wake-up may be spurious, so the condition may not hold
Waiting on a condition variable releases the lock and sleeps; when signaled, the thread reacquires the lock and returns. But before it does, another thread may grab the lock and take the queue element. Implementations are also allowed to wake a thread with no signal at all (a spurious wake-up). So the code checks the condition after waking and waits again if it does not hold, using a while loop.
Wake one if any of the waiting threads can handle the event equally well. Wake all when the threads wait for different conditions or when all of them need to re-check the situation.
A semaphore remembers a count; an increment made when no one is waiting can be used later. A condition variable remembers nothing, so it is always used together with a mutex and data representing the condition.
As an Amazon Associate I earn from qualifying purchases.
This page was drafted with AI and fact-checked by a separate AI review before publication. Our Editorial policy explains how we write and check content. If you spot an error, please tell us on our Contact page.