c++基础组件性能对比测试(2)std::mutex和atomic_flag

之前有人提及在linux下std::mutex性能没有atomic_flag快,大概差了一倍;

我今天在我的windows10以及vs2017上测试了一下,

1)在使用lock_guard情况下,多线程同步测试结果是一样;

2)在std::atomic<int>单纯无锁计算累计数据时候明显要快;

有其他网友分析windows vista以上版本mutex是使用的SRWLOCK,而不再是互斥段。

参考:https://blog.csdn.net/jiangdong2007/article/details/89513476

代码如下:

// 自旋锁的实现
class spin_lock {
public:
	spin_lock() = default;
	spin_lock(const spin_lock&) = delete;
	spin_lock& operator=(const spin_lock) = delete;
	void lock() {   // acquire spin lock
		while (flag.test_and_set()) {}
	}
	void unlock() {   // release spin lock
		flag.clear();
	}
private:
	atomic_flag flag;
};

spin_lock splock;
std::mutex myMutex;
int num = 0;
std::atomic<int> count1(0);
void addFunc1() 
{
	for (int i = 0; i < 1000000; ++i) 
	{
		//std::lock_guard<spin_lock> lock(splock); // 就是这里不一样!!!
		//num++;
		count1 ++;
	}
}

void addFunc2()
{
	for (int i = 0; i < 1000000; ++i)
	{
		std::lock_guard<std::mutex> lock(myMutex); // 就是这里不一样!!!
		num++;

	}
}

int main() {

	Timer timer1;
	timer1.start();
	thread t1(addFunc1);
	thread t2(addFunc1);
	thread t3(addFunc1);
	t1.join();
	t2.join();
	t3.join();
	auto duration2 = timer1.stop_delta<std::milli>();
	std::cout << "耗时(ms): " << duration2 << endl;
	std::cout << count1 << endl;

	return 0;
}

 

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值