简体   繁体   English

分配等效于std :: atomic的加载/存储<bool>

[英]Is assignment equivalent to load/store for std::atomic<bool>

I see that this is potentially answered in question Must I call atomic load/store explicitly? 我看到这可能是有问题的答案。 我必须显式调用原子加载/存储吗? .

So for sake of clarity I will restate my question succinctly in the hopes that future readers find this clear. 因此,为了清楚起见,我将简要地重申我的问题,希望将来的读者能清楚地理解。

Is

std::atomic<bool> b(false);
bool x = b;

Same as 和...一样

std::atomic<bool> b(false);
bool x = b.load();

And

std::atomic<bool> b(false);
b = true;

Same as 和...一样

std::atomic<bool> b(false);
b.store(true);

If this is indeed the case then: 如果确实如此,则:

  1. why have 2 options? 为什么有2个选择? what is the apparent benefit? 明显的好处是什么?
  2. Is it good practice when dealing with atomics to prefer the more verbose load()/store() over the potentially confusing assignment(=) which could mean either depending on whether LHS or RHS is the atomic. 与原子打交道时,是否使用更冗长的load()/ store()而不是可能引起混淆的赋值(=),这是一种好习惯,这可能取决于LHS或RHS是原子。

NOTE I am already aware of the fact that both variables cannot be std::atomic ie LHS and RHS as it is not possible to read and write atomically in one instruction. 注意:我已经意识到以下事实:两个变量不能为std :: atomic,即LHS和RHS,因为不可能在一条指令中进行原子读写。

Yes, they are the same. 是的,它们是相同的。 I think the reason the overloaded operators are provided is for convenience. 我认为提供重载运算符的原因是为了方便。 Not to mention making it easier to convert existing code to use atomics. 更不用说使将现有代码转换为使用原子更容易了。

Personally, I prefer to be explicit with load and store always. 就个人而言,我宁愿对loadstore始终保持明确。 I think it's better practice and forces you to remember that you're dealing with an atomic. 我认为这是更好的做法,它会迫使您记住您正在处理原子。

Also, those functions allow you to specify other memory orders, which is not possible with the overloaded operator versions. 此外,这些功能还允许您指定其他存储顺序,这对于重载的操作员版本是不可能的。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM