#include
#include
#include
#include<Windows.h>
using namespace std;
int counter = 0;
std::mutex mtx;
void func1()
{
while (true)
{
//Sleep(1);
//std::unique_lockstd::mutex lock(mtx);
if (counter < 100)
{
counter++;
cout << "func1 " << counter << endl;
}
else
{
break;
}
}
}
void func2()
{
while (true)
{
//Sleep(1);
//std::unique_lockstd::mutex lock(mtx);
if (counter < 100)
{
counter++;
cout << "func2 " << counter << endl;
}
else
{
break;
}
}
}
int main()
{
std::thread th1(func1);
std::thread th2(func2);
th1.join();
th2.join();
system(“pause”);
return 0;
}
执行结果:
出现打印乱码,而且顺序不是递加的。
采用同步之后,加了锁之后:(把注释的代码放开之后)
很整齐和很递增
什么时候加锁,在哪加锁是多线程的很重要的一个问题
线程同步和加锁的机制
最新推荐文章于 2023-10-14 20:02:37 发布