+在c ++中的运算符的线程安全性 [英] Thread safety of += operator in c++
本文介绍了+在c ++中的运算符的线程安全性的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!
问题描述
是否是c ++线程安全的 + =
运算符?
Is the +=
operator in c++ thread-safe?
可以想象一种情况,它不是(Pseudocode):
It is possible to imagine a situation where it is not (Pseudocode):
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 ("%d\n", a);
}
很明显,当+ =重载时,我必须使用Mutexes,
It is obvious, that i must use Mutexes when += is overloaded, but do i have to set a mutex when working with simple types?
推荐答案
这是不是
为了获得同步行为而不使用阻塞(mutexes),你可以使用C ++ 11包装器 std :: atomic
。
To get synchronized behaviour without using blocking (mutexes) you could e.g. use the C++11 wrapper 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.
}
这篇关于+在c ++中的运算符的线程安全性的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!
查看全文