'Spurious wakeup with atomics and condition_variables
std::atomic<T>
and std::condition_variable
both have member wait
and notify_one
functions. In some applications, programmers may have a choice between using either for synchronization purposes. One goal with these wait
functions is that they should coordinate with the operating system to minimize spurious wakeups. That is, the operating system should avoid waking the wait
-ing thread until notify_one
or notify_all
are called.
On my machine, sizeof(std::atomic<T>)
is sizeof(T)
and sizeof(std::condition_variable)
is 72. If you exclude std::atomic<T>
's T
member, then std::condition_variable
reserves 72 bytes for to serve its synchronization purposes while sizeof(std::atomic<T>)
reserves 0 bytes.
My question: should I expect different behavior between std::condition_variable
's and std::atomic<T>
's wait
functions? For example, should std::condition_variable
have fewer spurious wakeups?
Solution 1:[1]
My question: should I expect different behavior between
std::condition_variable
's andstd::atomic<T>
'swait
functions? For example, shouldstd::condition_variable
have fewer spurious wakeups?
std::atomic::wait
does not have spurious wake ups. The standard guarantees that a changed value was observed, it says in [atomics.types.generic.general]/30:
Effects: Repeatedly performs the following steps, in order:
(30.1) Evaluates load(order) and compares its value representation for equality against that of old.
(30.2) If they compare unequal, returns.
(30.3) Blocks until it is unblocked by an atomic notifying operation or is unblocked spuriously.
So, if the underlying implementation of atomic wait makes spurious wake ups, they are hidden by the C++ standard library implementation.
If your questions is about whether there are more or fewer spurious wakeups in the underlying implementation of atomics or condition variables, then it is implementation specific. Will depend on operating system and library implementation. Most likely answer is: no, because the ultimate implementation, where OS makes kernel call is highly likely the same.
Sources
This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.
Source: Stack Overflow
Solution | Source |
---|---|
Solution 1 | Alex Guteniev |