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.
std::atomic<T>::load Atomically loads and returns the current value of the atomic variable. Memory is affected according to the value of order .
The Atomic Shop is the microtransaction store for spending Atoms ( ) in Fallout 76.
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.
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.
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.
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