Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

What is the difference between explicit atomic load/store and usual operator= and operator T?

Consider these two variants:

std::atomic<int> a;
a = 1;
int b = a;

and

std::atomic<int> a;
a.store(1);
int b = a.load();

I see from the documentation that the second one is fully atomic, but I don't understand when I should use which and what's the difference in detail.

like image 971
Juster Avatar asked Sep 09 '14 08:09

Juster


People also ask

What does STD atomic load do?

std::atomic<T>::load Atomically loads and returns the current value of the atomic variable. Memory is affected according to the value of order .

What is an atomic store?

The Atomic Shop is the microtransaction store for spending Atoms ( ) in Fallout 76.

What is atomic store c++?

atomic::storeAtomically replaces the current value with desired . Memory is affected according to the value of order . order must be one of std::memory_order_relaxed, std::memory_order_release or std::memory_order_seq_cst. Otherwise the behavior is undefined.

What is std :: atomic?

Each instantiation and full specialization of the std::atomic template defines an atomic type. Objects of atomic types are the only C++ objects that are free from data races; that is, if one thread writes to an atomic object while another thread reads from it, the behavior is well-defined.


1 Answers

Those two examples are equivalent; operator= and operator T are defined to be equivalent to calling store and load respectively, with the default value for the memory_order argument.

If you're happy with that default value, memory_order_seq_cst, so that each access acts as a memory fence, then use whichever looks nicer to you. If you want to specify a different value, then you'll need to use the functions, since the operators can't accept a second argument.

like image 107
Mike Seymour Avatar answered Oct 08 '22 13:10

Mike Seymour