multithreadingpthreadslockingcondition-variablespurious-wakeup

POSIX condition variables VS Win32 Event Objects (about spurious wakeup problem)


In POSIX, because of "spurious wakeup" problem, programmers are forced to use while() instead of if when checking condition.

I think spurious wakeup is unintuitive and confusing problem, but I thought it's an inevitable problem.

Recently, I found that event objects of win32 doesn't have "spurious wakeup" problem.

Why POSIX system and other systems still use condition variable which has "spurious wakeup" problem? (despite this can be solved?)


Solution

  • You ask:

    Why POSIX system and other systems still use condition variable which has "spurious wakeup" problem? (despite this can be solved?)

    Basically, it's faster than the alternative.

    The RATIONALE section of the POSIX.1-2017 treatment of pthread_cond_broadcast and pthread_cond_signal specifically has this to say about "Multiple Awakenings by Condition Signal":

    While [the "spurious wakeup"] problem could be resolved, the loss of efficiency for a fringe condition that occurs only rarely is unacceptable, especially given that one has to check the predicate associated with a condition variable anyway. Correcting this problem would unnecessarily reduce the degree of concurrency in this basic building block for all higher-level synchronization operations.

    Emphasis added.

    The text further observes that forcing "a predicate-testing-loop around the condition wait" is a more robust coding practice than the alternative, because the application will necessarily tolerate superfluous broadcasts and signals from elsewhere in the code.