#include <thread>
#include <iostream>
#include <mutex>
std::mutex m;
int count=10;
bool debug=true;//控制 是否使用互斥
using std::cout;
using std::endl;
void hello1()
{
if(debug)
m.lock();
for(int i=0;i<1000;i++)
{
count++;
cout<<"1"<<std::flush;
}
if(debug)
m.unlock();
}
void hello2()
{
if(debug)
m.lock();
for(int i=0;i<1000;i++)
{
count--;
cout<<"2"<<std::flush;
}
if(debug)
m.unlock();
}
int main()
{
std::thread t1(hello1),t2(hello2);
t1.join();
t2.join();
std::cout<<"Main Thread "<<count<<std::endl;
return 0;
}
多线程互斥 基于c++11
最新推荐文章于 2023-02-08 17:03:27 发布