c++中+=操作符的线程安全性
Thread safety of += operator in c++
+=
操作符是c++线程安全的吗?
可以想象它不是(伪代码)的情况:
int a = 5;
void thread1 () {
a += 5;
}
void thread2 () {
a += 5;
}
void main () {
start_thread1 ();
start_thread2 ();
//Prints 15 always, but i think 10 is not impossible.
printf ("%dn", a);
}
很明显,当+=被重载时,我必须使用互斥锁,但是当使用简单类型时,我必须设置互斥锁吗?
+=
不是原子的,所以它确实不是线程安全的,你可以得到10
。或者,坦率地说,奶牛被从月球上赶出来。也许披萨会出现在你的狗鼻子周围。
是线程安全。
要获得同步行为而不使用阻塞(互斥锁),您可以使用c++ 11包装器std::atomic
。
std::atomic<int> a{5};
void work() {
a += 5; // Performed atomically.
}
int main() {
std::thread t1{work};
std::thread t2{work};
t1.join();
t2.join();
std::cout << a << std::endl; // Will always output 15.
}
相关文章:
- 类与私有变量的其他类之间的线程安全性
- 调用socket.remote_endpoint(提升 asio 库)线程安全性
- std::lock_guard 似乎提供了线程安全性,尽管作用域块
- C++中向量和列表的非写入成员函数的线程安全性
- 线程安全性和静态变量/成员功能
- 是仅使用get或toplown的原始类型的线程安全性的威胁
- 提高 ASIO stream_descriptor和事件 FD 线程安全性
- OpenMP中树结构的线程安全性
- 静态变量初始化的线程安全性
- 从另一个(非 qt)线程调用 QObject 方法的线程安全性?
- C 共享_ptr如何确保线程安全性
- 编写std::vector与普通数组的线程安全性
- C++标准库容器相对于所包含对象的线程安全性
- 读取和写入操作的线程安全性C++
- Qt库-静态成员函数的线程安全性
- QObject可重入性和线程安全性
- std::map中的线程安全性
- boost::asio io_service 和 std::containers 的线程安全性
- C++11 std:原子<T>复制构造函数的线程安全性
- Clang 线程安全性分析和线程角色