比较操作线程对 std::atomic 变量是安全的吗?

Is a comparison operation thread safe for std::atomic variables?

本文关键字:安全 变量 atomic 操作 线程 std 比较      更新时间:2023-10-16

std::atomic有一些运算符,如:+,-,++,-(post和pre),并保证它们是线程安全的,但是比较操作线程安全吗?我的意思是:

std::atomic<int> a = 10;
int i = 20;
void func() {
  a++; // atomic and thread safe
  if (a > i) // is it thread safe? 
}

只有在以下情况下,这才是线程安全的:

  • i永远不会改变(你真的应该让它const
  • 你不会期望如果a++将值更改为大于i,则连续的原子载荷将满足a > i。 两个独立的原子指令不是原子的。
  • 您不需要分支代码是原子的

请注意这里的最后一点。 您可以自由比较a > i. 这将以原子方式获取a的当前值,然后使用该值与i进行比较。 但是,a的实际值可能会立即更改。 只要您的分支不依赖于这种情况不发生,这就可以了。

if( a > i )
{
    // a is not guaranteed to be greater than i at this point.
}

我不太确定您希望逻辑如何工作,但您可能是这个意思:

if( ++a > i )
{
    // a is still not guaranteed to be greater than i at this point,
    // but AT THE TIME OF INCREMENTING it did exceed i.
}