比较操作线程对 std::atomic 变量是安全的吗?
Is a comparison operation thread safe for std::atomic variables?
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.
}
相关文章:
- 全局变量 多读取器 一个写入器多线程安全?
- 静态 constexpr 类成员变量对多线程读取是否安全?
- 在函数结束后使用指向变量的指针是否安全?
- C++线程安全:如果只有一个线程可以写入非原子变量,但多个线程从中读取. 会遇到问题吗?
- C++11如何在1个线程中使用条件变量处理2个线程安全队列
- C++:用IIFE线程初始化静态局部变量安全吗
- std::mutex作为一个成员变量对多个线程来说是安全的吗
- 为什么我的 std::atomic<int> 变量不是线程安全的?
- 将常量引用成员设置为临时变量是否安全
- 是局部unordered_map变量线程在C 中安全的线程
- 如何修复编译错误"此函数或变量可能不安全"(strcpy)
- 为什么静态局部变量的 MSVC 线程安全初始化使用 TLS
- 将自动类型变量初始化为零.这种类型安全吗?
- 定义,初始化全局const变量是安全的吗?
- 当空变量没有定义时,按值传递它们是否安全
- 使用函数模板中静态局部变量的地址作为类型标识符是否安全
- 如何使类静态变量线程安全
- 使用局部静态std :: ARNE_FLAG和局部静态指针对静态变量的线程安全初始化
- C++ - "本地时间" 此函数或变量可能不安全
- 用C++设计线程安全变量类