#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...