Synchronization PrimitivesCondition VariablesMedium⏱️ ~2 min

The Wait Loop Pattern

Key Insight
Always wait in a loop. This is the most important rule when using condition variables: never check the condition with just an if statement.
Wait Pattern Comparison
WRONG: if statementif (queue.empty()) cond.wait(lock);Spurious wake = BUG!Stolen wake = BUG!CORRECT: while loopwhile (queue.empty()) cond.wait(lock);Spurious wake = retryStolen wake = retry

Why Spurious Wakes Happen

The system may wake your thread even when no signal was sent. This is a performance optimization in pthread implementations. Your code must handle it.

Why Stolen Wakes Happen

Thread A signals that an item is available. Thread B wakes up. But before B can acquire the mutex, Thread C (which was not waiting) swoops in, takes the item, and leaves. B finally gets the mutex, but the queue is empty again.

The While Loop Saves You

With a while loop, you check the condition after every wake. If the condition is still false (spurious wake or stolen wake), you go back to waiting. Simple and bulletproof.

lock(mutex)
while (!condition)
  wait(cond, mutex)
// condition is now true
do_work()
unlock(mutex)
Pattern: lock → while(!condition) wait → do_work → unlock. Never deviate from this.
💡 Key Takeaways
Always use while (condition) cond.wait(), never if (condition) cond.wait().
Spurious wakeups: threads may wake without signal. OS allows this for performance.
Race after signal: another thread may make condition false between signal and your wakeup.
Broadcast wakes all, but condition may only allow one. Others must wait again.
The while loop is a standard pattern in all languages: Java, C++, Python, Go.
📌 Interview Tips
1Producer consumer: while (count == 0) notEmpty.wait(mutex); // consumer waits until items available
2Bounded buffer: while (count == MAX) notFull.wait(mutex); // producer waits until space available
← Back to Condition Variables Overview