求问这个C++的并发程序?-灵析社区

无敌铃铃后

#include using namespace std; std::atomic counter(0); void increment() { for (int i = 0; i < 100000; ++i) { counter.store(counter.load() + 1); } } int main() { std::thread t1(increment); std::thread t2(increment); t1.join(); t2.join(); std::cout << "Counter: " << counter.load() << std::endl; return 0; } 为啥最后打印类似100475,100425之类的值? 我看写这个的人说会打印200000.

阅读量:158

点赞量:0

问AI
你先获取当前值,然后存入当前值+1,这之间如果有其它线程读取了 "counter" 的值,那么可能会重复操作。例如: 线程 1:load 345 线程 2: load 345 线程 2: store 346 线程 1: store 346 将代码修改为直接 +1 即可: counter.fetch_add(1);