Synchronization

a spurious wakeup

You set an alarm to ring when the kettle boils. Now and then you jolt awake even though the kettle is still cold — a false alarm. A spurious wakeup is the same thing for a thread waiting on a condition variable: it returns from wait even though no other thread signalled it, or the condition it was waiting for is not actually true. It woke up for no good reason.

Why does this happen at all? On many systems, waking the right waiter precisely is expensive, and certain low-level events (a signal delivered to the thread, or an implementation that wakes several waiters to avoid a more costly bookkeeping) can cause wait to return early. The C, C++, and POSIX standards explicitly permit it, which means you may never assume that returning from wait implies the condition is true. The defence is simple and mandatory: always wait inside a loop that re-tests the predicate — write while (!ready) cond_wait(&cv, &m); rather than if (!ready) cond_wait(&cv, &m);. If the wakeup was spurious, the loop sees the predicate is still false and goes straight back to sleep; no harm done.

Spurious wakeups are the textbook reason the wait-while-predicate pattern is not optional. Even on a platform that never produced one, the loop is still required, because a real signal can race: another thread may have woken you legitimately, but a third thread grabbed the lock and consumed the resource before you re-acquired it, so the predicate is false again. Treating a wakeup as merely a hint to re-check — never as a guarantee — makes your code correct under both spurious wakeups and ordinary races, with no extra effort.

Wrong: if (queue_empty) cond_wait(&cv, &m); item = dequeue(); — a spurious wakeup can dequeue from an empty queue. Right: while (queue_empty) cond_wait(&cv, &m); item = dequeue();.

The while loop turns a spurious or stale wakeup into a harmless re-check.

Spurious wakeups are real but rare; do not 'test for' them or special-case them. The single correct response is to always loop on the predicate, which also protects you against legitimate but stale wakeups — so you never even need to know which kind it was.

Also called
false wakeupspurious wake假性喚醒