liveBook · Manning

Spurious wakeup

As explained in C++ Concurrency in Action, Second Edition

A spurious wakeup is a return from a condition-variable wait without a notification that makes the awaited condition true.

A spurious wakeup occurs when a condition-variable wait reacquires its mutex and checks the condition without a notification causing that check. A wake is not proof that the awaited state is true: keep checking the condition, preferably with the predicate form of wait. The predicate may be checked repeatedly while the mutex is locked, so avoid side effects in it. section 4.1.1

For timed waits, repeated relative timeouts can restart the full wait after each spurious wake and make the total wait unbounded. Use one fixed deadline and check the condition in a loop. section 4.3.3

template<typename Predicate>
void minimal_wait(std::unique_lock<std::mutex>& lk,Predicate pred){
    while(!pred()){
        lk.unlock();
        lk.lock();
    }
}

A minimal wait implementation loops until the predicate is true, unlocking and relocking around each check. section 4.1.1

How C++ Concurrency in Action, Second Edition covers it

How deep it goes
Defines spurious wakes, explains predicate rechecking and side-effect risks, and contrasts fixed-deadline waits with repeated relative timeouts.
Examples
Uses a queue-nonempty predicate and a 500-millisecond wait-until loop to illustrate condition rechecking.
What you can do after
Apply it via std::condition_variable by rechecking the predicate and bounding timed waits with one deadline.
How it connects
Connects condition variables to predicates, mutexes, timed waits, and producer-consumer queues.

This explainer was generated by Manning's knowledge graph from the text of C++ Concurrency in Action, Second Edition. The section links point to the parts of the book it draws on.