Course contentsShow
← Computer Science
Lesson 1308 of 2,87230. Process SynchronizationFree lesson

Spurious Wakeups

Understand spurious wakeups and why wait() must always be called inside a while loop checking the condition.

Spurious Wakeups

You'll learn why condition variable waits can wake up unexpectedly and how to protect your code from this behavior.

What Is a Spurious Wakeup?

A spurious wakeup occurs when a thread waiting on a condition variable wakes up without anyone explicitly signaling it. The thread returns from wait() even though the condition it was waiting for might not actually be true yet.

This can happen due to implementation details in the threading library, operating system scheduler decisions, or subtle timing issues in multiprocessor systems. The key insight: you cannot trust that your condition is true just because wait() returned.

Why This Matters

Imagine you're waiting in line at a bakery (waiting on a condition variable). The baker is supposed to ring a bell when fresh bread is ready (the signal). But sometimes the bell rings accidentally, or you mishear something else as the bell. If you blindly grab for bread without checking if it's actually ready, you'll be disappointed—or worse, cause problems.

This is why you must always wrap wait() inside a while loop that re-checks your condition:

pthread_mutex_lock(&mutex);
while (!condition_is_true) {  // WHILE, not IF!
    pthread_cond_wait(&cond, &mutex);
}
// Now safe to proceed: condition is definitely true
pthread_mutex_unlock(&mutex);

Using while instead of if ensures that even if the thread wakes spuriously, it immediately re-checks the condition and goes back to waiting if needed.

The Pattern in Practice

Every time your thread wakes from wait(), the while loop verifies the actual state. If the condition is false (spurious wakeup), it waits again. If true (legitimate signal), it proceeds safely.

Key Takeaway: Always use a while loop—never if—around pthread_cond_wait() to guard against spurious wakeups and ensure your condition is genuinely satisfied before proceeding.