c ++中+ =运算符的线程安全性

时间:2014-05-15 12:30:17

标签: c++ multithreading thread-safety

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 ("%d\n", a);
}

很明显,当+ =重载时我必须使用互斥锁,但是在使用简单类型时我是否必须设置互斥锁?

2 个答案:

答案 0 :(得分:7)

+=不是原子的,所以它确实不是线程安全的,你可以获得10。或者,坦率地说,奶牛被从月球中射出。也许披萨在你的狗的鼻子周围出现。

答案 1 :(得分:6)

线程安全。

要在不使用阻止(互斥锁)的情况下获得同步行为,您可以例如使用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.
}