c++c++20stdatomicspurious-wakeup

std::atomic<T>::wait - is spurious wakeup possible or not?


cppreference regarding std::atomic<T>::wait:

void wait( T old, std::memory_order order =
                     std::memory_order::seq_cst ) const noexcept;

Performs atomic waiting operations. Behaves as if it repeatedly performs the following steps:

  • Compare the value representation of this->load(order) with that of old. If those are equal, then blocks until *this is notified by notify_one() or notify_all(), or the thread is unblocked spuriously.
  • Otherwise, returns.

These functions are guaranteed to return only if value has changed, even if underlying implementation unblocks spuriously.

I'm confused, do I need to care about spurious wakeups - which means wait() can return even the value is still old - or not?


Solution

  • You don't need to care about spurious wakeups.
    wait() will not return if the value is still old.

    This is understood from the following in the documentation you quoted:

    1. It is mentioned that the steps that the behavior should be like (including the possibility of spurious wakeup) are done repeatedly, so even if a spurious wakeup accurs wait() will not return and will continue to loop comparing the result of load() with the value of old.

    2. Just to make sure it is clear, the documentation explicitly mentions that:

      These functions are guaranteed to return only if value has changed, even if underlying implementation unblocks spuriously.

      (emphasis is mine)