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.
}
关于c++ - std::atomic 变量的比较操作线程安全吗?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/34939041/