Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Difference between std::atomic and std::condition_variable wait, notify_* methods

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.

like image 851
PVRT Avatar asked Jul 12 '20 09:07

PVRT


People also ask

What is std :: Condition_variable?

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 .

What is the difference between Notify_one and Notify_all?

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.

How fast is STD Atomic?

std::atomic<bool> On average, the execution time is 0.38 seconds.

What does condition variable wait do?

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).


1 Answers

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:

  • If the values are equal, it blocks the thread until notified by notify_one or notify_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:

  • Linux: default to futex (with table), fallback to futex (no table) -> CVs -> timed backoff -> spin.
  • Mac: default to CVs (table), fallback to timed backoff -> spin.
  • Windows: default to futex (no table), fallback to timed backoff -> spin.
  • CUDA: default to timed backoff, fallback to spin. (This is not all checked in in this tree.)
  • Unidentified platform: default to spin.
like image 123
alex_noname Avatar answered Oct 12 '22 22:10

alex_noname