C++11中10个线程同时竞争资源,会出现竞争问题
处理方式1,mutex
#include<iostream>
#include<vector>
#include<thread>
#include<functional>
#include <time.h>
#include<atomic>
#include<mutex>
using namespace std;
mutex mut;
void func(int &counter)
{
mut.lock();
for(int i=0;i<100001;++i)
++counter;
mut.unlock();
}
int main()
{
clock_t start = clock();
int counter=0;
vector<thread> threads;
for(int i=0;i<10;++i)
{
threads.push_back(thread{func,ref(counter)});
}
for(auto &t:threads)
{
t.join();
}
clock_t finish = clock();
cout<<"Result = "<<counter<<endl;
cout<<"duration:"<<finish -start<<"ms"<<endl;
return 0;
}
处理方式2:原子操作
#include<iostream>
#include<vector>
#include<thread>
#include<functional>
#include <time.h>
#include<atomic>
#include<mutex>
using namespace std;
//mutex mut;
void func(atomic<int> &counter)
{
//mut.lock();
for(int i=0;i<100001;++i)
++counter;
//mut.unlock();
}
int main()
{
clock_t start = clock();
atomic<int> counter(0);
vector<thread> threads;
for(int i=0;i<10;++i)
{
threads.push_back(thread{func,ref(counter)});
}
for(auto &t:threads)
{
t.join();
}
clock_t finish = clock();
cout<<"Result = "<<counter<<endl;
cout<<"duration:"<<finish -start<<"ms"<<endl;
return 0;
}