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::condition_variable The condition_variable class is a synchronization primitive that can be used to block a thread, or multiple threads at the same time, until another thread both modifies a shared variable (the condition), and notifies the condition_variable .
Show activity on this post. If there are ten threads blocked on the condition variable, for example, notify_one() will unblock only one thread, while notify_all() will unblock them all. In your case, you'll want to use notify_one() so you don't wake up threads that don't have any work waiting for them.
std::atomic<bool> On average, the execution time is 0.38 seconds.
condition_variable::wait wait causes the current thread to block until the condition variable is notified or a spurious wakeup occurs, optionally looping until some predicate is satisfied (bool(stop_waiting()) == true).
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 modifies. It takes an argument to compare with the value of the atomic object. And it repeatedly performs:
notify_one
or notify_all
, or the thread is unblocked spuriously.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:
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With