What is a Condition Variable?
Why Not Just Use A Mutex?
Imagine waiting for a queue to have items. With just a mutex, you would have to lock, check, unlock, repeat. This busy-waiting wastes CPU. A condition variable lets you sleep efficiently until something changes.
The Three Operations
wait(mutex): Release the mutex, sleep, and when woken, reacquire the mutex before returning. All three steps are atomic from the caller's perspective.
signal(): Wake up one waiting thread. If no one is waiting, the signal is lost.
broadcast(): Wake up all waiting threads. They will compete for the mutex.
Think Of It Like A Doctor's Waiting Room
You check in (acquire mutex), see no doctor available, sit down and wait (wait). When a doctor becomes free, the receptionist calls your name (signal). You then go into the consultation (reacquire mutex and proceed).