#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 发布
本文通过一个C++程序示例介绍了如何使用互斥锁(mtx)来实现多线程间的同步操作,确保共享资源的安全访问。在示例中,两个线程分别对全局变量进行递增和递减操作,通过控制debug变量可以开启或关闭互斥锁。

1005

被折叠的 条评论
为什么被折叠?



