c++中+=操作符的线程安全性

Thread safety of += operator in c++

本文关键字:线程 安全性 操作符 c++      更新时间:2023-10-16

+=操作符是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.
}