If I have an atomic variable, e.g.,
std::atomic<int> x;
and I want to perform reads and writes on it, I can use the "normal" syntax, e.g.,
std::cout << x; // read from x
x = 5; // write to x
I can also use the explicit load
and store
member functions:
std::cout << x.load(); // read from x
x.store(5); // write to x
I've seen recommendations by people like Andrei Alexandrescu and Anthony Williams to use only the explict load
and store
forms, presumably because the "normal" forms don't emphasize that the variables are atomic. That seems almost like a form of Hungarian notation. Is there an emerging convention on the syntax to use when reading and writing atomics?
Several operations are overloaded to "do what you think", and to do this with sequentially consistent memory ordering. So:
int n = x;
is the same as int n = x.load(std::memory_order_seq_cst)
, andx = 1
is the same as x.store(1, std::memory_order_seq_cst)
.However, if you want any kind of relaxed memory ordering, you need to use the explicit member function, e.g. int n = x.load(std::memory_order_acquire)
.
The idea is that "natural" looking code will generally be correct (recall the "sequentially consistent for data-race-free programs" execution model), but riskier, more aggressive operations are available – they just have to be explicit.
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