What is a condition variable and why does wait() release the lock?
A condition variable lets a thread sleep until some condition becomes true. wait() atomically releases the lock and sleeps so other threads can change the state; on wakeup the thread reacquires the lock and rechecks.
Explain it simply
Suppose you wait at a railway counter for a ticket to become available. If you stood at the window holding it shut, nobody could issue a ticket. So you step away and wait on a bench, and the clerk calls you when one is ready.
A condition variable works the same way. The thread holds a lock, finds the condition false, and calls wait(). That does two things atomically: releases the lock and puts the thread to sleep. Another thread then takes the lock, changes the state, and calls signal(). The sleeper wakes, reacquires the lock, and continues.
Example
// consumer
lock(m)
while (queue is empty) // a while, not an if
wait(notEmpty, m) // releases m, sleeps, reacquires m on wakeup
item = queue.remove()
unlock(m)
// producer
lock(m)
queue.add(item)
signal(notEmpty)
unlock(m)The while loop is essential. Between the signal and the consumer running, another consumer may have taken the item, and some systems wake threads spuriously. Rechecking the condition on every wakeup makes the code correct in all cases.
What to say in the interview
"A condition variable lets a thread wait inside a lock-protected region until a condition holds. wait atomically releases the mutex and sleeps, then reacquires it on wakeup. I always wait in a while loop because of stolen wakeups and spurious wakeups."
Common mistakes
- Using if instead of while around wait().
- Signalling without holding the lock that protects the condition.