Common Condition Variable Pitfalls
You'll learn the three most frequent mistakes that break condition variable synchronization.
Condition variables are powerful, but easy to misuse. Even experienced developers stumble into these traps, causing hard-to-debug race conditions and deadlocks.
Pitfall 1: Forgetting the Mutex
Never call wait() or signal() without holding the associated mutex. The mutex protects the shared state your condition is checking. Calling wait() without locking first leads to undefined behavior—you might check stale data or miss signals entirely.
Analogy: It's like checking if a package arrived (condition) without first locking the mailbox (mutex)—someone could deliver it between your check and your decision to wait.
Pitfall 2: Using if Instead of while
Always use a while loop to check conditions, not an if statement:
// WRONG
if (count == 0) {
pthread_cond_wait(&cond, &mutex);
}
// CORRECT
while (count == 0) {
pthread_cond_wait(&cond, &mutex);
}
Why? Spurious wakeups can occur, and other threads might change the condition between the signal and your wakeup. The while loop rechecks after every wakeup, ensuring the condition actually holds.
Pitfall 3: Incorrect Signal Placement
Call signal() or broadcast() while holding the mutex, and do so after modifying the shared state:
pthread_mutex_lock(&mutex);
count++; // Modify state FIRST
pthread_cond_signal(&cond); // Then signal
pthread_mutex_unlock(&mutex);
Signaling before changing state creates a race: waiting threads might wake up, recheck the condition, and find it still false.
Key Takeaway: Always pair condition variables with mutexes, use while (never if) to check conditions, and signal only after modifying state while holding the lock. These pitfalls cause the majority of condition variable bugs.