多线程:手动互斥和原子操作的 耗时对比

#include <iostream>
#include <thread>
#include <mutex>	// 互斥锁
#include <atomic>	// 原子操作
#include <ctime>

using namespace std;
/*
mutex,很好地解决了多线程资源争抢的问题,但它也有缺点:太……慢……了…… ,每次循环都要加锁、解锁,会浪费很多的时间
atomic,本意为原子,原子操作是最小的且不可并行化的操作: 即使是多线程,也要像同步进行一样同步操作atomic对象。从而省去了mutex上锁、解锁的时间消耗。
*/

//----#1 互斥锁:线程执行函数内部手动开锁、解锁
std::mutex mtx; // 全局互斥锁
int shared_resource_mutex = 0;
void increment() {
	for (int i = 0; i < 1e7; ++i) {
		mtx.lock(); // 锁定互斥锁
		(++shared_resource_mutex);
		//cout<<"\t shared_resource = "<<shared_resource<<endl;
		mtx.unlock(); // 解锁互斥锁
	}
}
//----#2 原子操作:线程执行函数内部不可并行
atomic_int shared_resource_atomic = 0;
void increment1() {
	for (int i = 0; i < 1e7; ++i) {		
		(++shared_resource_atomic);	//原子操作
		//cout<<"\t shared_resource_atomic = "<<shared_resource_atomic<<endl;
	}
}


int main() {
	//----#1 互斥锁:多线程操作耗时
	auto time1	  = clock();	
		thread t1(increment);
		thread t2(increment);
		thread t3(increment);
		t1.join();
		t2.join();
		t3.join();
	auto time2	  = clock();	
		cout<<"多线程-用互斥锁:\n\t shared_resource_mutex = "<<shared_resource_mutex;
		cout<<"\n\t, time2  - time1  = "<<time2<<" -  "<<time1<<"  = "<<time2-time1<<" us"<<endl;
	
	//----#2 原子操作:多线程操作耗时
	auto time11	  = clock();	
		thread t11(increment1);
		thread t12(increment1);
		thread t13(increment1);
		t11.join();
		t12.join();
		t13.join();
	auto time12	  = clock();	
		cout<<"多线程-原子操作:\n\t shared_resource_atomic= "<<shared_resource_atomic;
		cout<<"\n\t, time12 - time11 = "<<time12<<" - "<<time11<<" = "<<time12-time11<<" us"<<endl;
	
	
	return 0;
}

============= 运行结果 ==============

多线程-用互斥锁:
         shared_resource_mutex = 30000000
        , time2  - time1  = 1294 -  0  = 1294 us
多线程-原子操作:
         shared_resource_atomic= 30000000
        , time12 - time11 = 1908 - 1294 = 614 us

--------------------------------
Process exited after 2.017 seconds with return value 0 (1078 ms cpu time, 948 KB mem used).

Press ANY key to exit...

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值