繁体   English   中英

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

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM