#include "iostream"
#include "thread"
#include "mutex"
using namespace::std;
int aa=0; //定义全局变量
mutex mtx;//创建互斥锁,保护共享资源aa变量。
//普通函数,把全局变量加1000000次。
void func()
{
for (int ii = 0; ii < 1000000; ++ii) {
cout<<"线程"<<this_thread::get_id()<<"申请加锁"<<endl;
mtx.lock();
cout<<"线程"<<this_thread::get_id()<<"加锁成功"<<endl;
aa++;
this_thread::sleep_for(chrono::seconds(2));
mtx.unlock();
cout<<"线程"<<this_thread::get_id()<<"释放了锁"<<endl;
this_thread::sleep_for(chrono::seconds(1));
}
}
void func1()
{
for (int ii = 0; ii < 1000000; ++ii) {
lock_guard<mutex> mlock(mtx);
aa++;
}
}
int main()
{
// func();
// func();
//单线程输出2000000。
//多线程输出1000000多一点。
//用普通函数创建线程。
thread t1(func1);//创建线程t1,把全局变量aa加1000000次。
thread t2(func1);//创建线程t2,把全局变量aa加1000000次。
t1.join();
t2.join();
cout<<"aa="<<aa<<endl;//显示全局变量aa的值。
}
aa=2000000
发表回复