[英]Should std::atomic variables use “normal” syntax or “load” and “store”?
If I have an atomic variable, eg, 如果我有一个原子变量,例如,
std::atomic<int> x;
and I want to perform reads and writes on it, I can use the "normal" syntax, eg, 我想对它执行读写操作,我可以使用“普通”语法,例如,
std::cout << x; // read from x
x = 5; // write to x
I can also use the explicit load
and store
member functions: 我也可以使用显式load
和store
成员函数:
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. 我看过Andrei Alexandrescu和Anthony Williams等人的建议只使用explict load
和store
形式,大概是因为“正常”形式并不强调变量是原子的。 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)
, and 与int n = x.load(std::memory_order_seq_cst)
,并且 x = 1
is the same as x.store(1, std::memory_order_seq_cst)
. x = 1
与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, eg int n = x.load(std::memory_order_acquire)
. 但是,如果您想要任何类型的宽松内存排序,则需要使用显式成员函数,例如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. 我们的想法是,“自然”外观代码通常是正确的(回想一下“顺序一致的数据竞争程序”执行模型),但风险更大,更积极的操作是可用的 - 它们只需要明确。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.