Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Should std::atomic variables use "normal" syntax or "load" and "store"?

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?

like image 441
KnowItAllWannabe Avatar asked Dec 25 '22 09:12

KnowItAllWannabe


1 Answers

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), and
  • x = 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.

like image 111
Kerrek SB Avatar answered Mar 21 '23 23:03

Kerrek SB