简体   繁体   中英

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?

std::atomic<T>::wait()

std::atomic<T>::notify_one()

std::condition_variable::wait()

std::condition_variable::notify_one()

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?

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.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM