std::atomic变量应该使用"normal"语法还是"load"和"store"?

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

本文关键字:load store 语法 std 变量 atomic normal      更新时间:2023-10-16

如果我有一个原子变量,例如

std::atomic<int> x;

并且我想对其进行读写操作,我可以使用"正常"语法,例如

std::cout << x;       // read from x
x = 5;                // write to x

我也可以使用显式的loadstore成员函数:

std::cout << x.load();       // read from x
x.store(5);                  // write to x

我看到像Andrei Alexandrescu和Anthony Williams这样的人建议只使用显式的loadstore形式,大概是因为"正常"形式不强调变量是原子的。这看起来像是匈牙利符号的一种形式。读写原子时使用的语法是否有新的约定?

有几个操作被重载为"做你想做的事",并且使用顺序一致的内存排序来做到这一点。所以:

  • int n = x;int n = x.load(std::memory_order_seq_cst)相同,
  • x = 1x.store(1, std::memory_order_seq_cst)相同。

然而,如果你想要任何一种宽松的内存排序,你需要使用显式成员函数,例如int n = x.load(std::memory_order_acquire)

这个想法是,看起来"自然"的代码通常是正确的(回想一下"无数据竞争的程序的顺序一致"执行模型),但风险更大,更激进的操作是可用的& & # ash;