Multicore & Synchronization
When waiting on a condition variable until a queue becomes non-empty, why is the condition rechecked in a while loop rather than an if after waking?
- AA while loop runs faster than an if statement
- BCondition variables cannot be used with if statements
- CEven after waking, another thread may have taken the item first or the wake-up may be spurious, so the condition may not hold
Show answer and explanation
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.
- A. It is not about speed.
- B. There is no such rule.
- C. Correct. The condition must be rechecked after waking.