I was looking through 'Atomic operations library' and came across a new c++20 feature of atomic 'wait' and 'notify_' methods. I am curious on what the differences are in regards to std::condition_variable's 'wait' and 'notify_' methods.
std:atomic wait
, notify_all
and notify_one
methods are similar to methods of conditional variables. They allow the implementation of the logic that previously required conditional variable by using much more efficient and lightweight atomic variables without using a mutex.
The wait
function blocks the thread until the value of the atomic object becomes different from a specific value. It takes an argument to compare with the value of the atomic object. And it repeatedly performs:
- If the values are equal, it blocks the thread until notified by
notify_one
ornotify_all
, or the thread is unblocked spuriously.- Otherwise, returns.
NOTE: wait
is guaranteed to return only if the value has changed, even if underlying implementation unblocks spuriously.
You can find the implementation here: https://github.com/ogiroux/atomic_wait/.
The strategy is chosen this way, by platform: