这段代码是线程安全的吗? (递增函数)

问题描述 投票:0回答:1

你觉得下面这段代码怎么样?

#include <iostream> 
#include <thread> 
using namespace std; 
 
static int cnt=0; 

void incr_fun() 
{ 
cnt=cnt+1; // incrementing counter 
} 

如果不是,我应该改变什么? 谢谢你

c++ thread-safety
1个回答
0
投票

不,它不是线程安全的。在任何线程执行

cnt
之前,多个线程可以同时读取
+1
并执行
cnt=
,反之亦然。

您需要使用

std::atomic
std::mutex
或任何其他等效的锁定机制来防止对共享资源的多个并发访问,例如:

#include <iostream> 
#include <thread> 
#include <atomic>
using namespace std; 
 
static atomic<int> cnt; 

void incr_fun() 
{ 
    ++cnt; // incrementing counter 
} 
© www.soinside.com 2019 - 2024. All rights reserved.