← Lessons

quiz vs the machine

Gold1440

Concurrency

Spurious Wakeups

Why wait can return without any thread signaling it.

4 min read · core · beat Gold to climb

Spurious Wakeups

A spurious wakeup is when a thread blocked on a condition variable returns from wait even though no other thread called notify and the condition it waited for is still false. It is a wakeup that nobody asked for.

Why does this happen? On many platforms the underlying signaling primitives can wake a waiter for implementation reasons, such as the way the operating system delivers signals or wakes groups of threads. Rather than forbidding this in the specification, most languages explicitly allow spurious wakeups and push responsibility onto the programmer.

The defense is simple and universal:

  • Always recheck the predicate in a loop after wait returns
  • If the condition is still false, simply call wait again
  • Never assume that returning from wait means the condition became true

In other words, treat wait as a hint that something might have changed, not a guarantee that it did. The loop turns a possibly false wakeup into a harmless extra check.

This is exactly why correct code is written as a while loop that tests the predicate, not a single if statement. An if statement would let a spuriously woken thread proceed as though the state were ready, which can corrupt the shared structure or violate an invariant. The while loop is the entire fix, and it also handles the case where multiple waiters are woken but only one can proceed.

Key idea

Wait may return with no signal and a false condition, so you must always recheck the predicate in a while loop rather than trusting that the wakeup means the state is ready.

Check yourself

Answer to earn rating on the learn ladder.

1. What is a spurious wakeup?

2. What is the correct defense against spurious wakeups?