3个线程轮流打印1~100
作者:
贺谦
,
2021-09-07 11:29:51
,
所有人可见
,
阅读 436
#include <iostream>
#include <thread>
#include <mutex>
using namespace std;
mutex mtx;
int i = 0;
condition_variable cv;
int flag = 0;
void print0()
{
unique_lock<mutex> ul(mtx);
while (true)
{
while (flag != 0)
{
cv.wait(ul);
}
flag = 1;
if (++ i > 100)
{
cv.notify_all();
break;
}
cout << "print0: " << i << endl;
cv.notify_all();
}
}
void print1()
{
unique_lock<mutex> ul(mtx);
while (true)
{
while (flag != 1)
{
cv.wait(ul);
}
flag = 2;
if (++ i > 100)
{
cv.notify_all();
break;
}
cout << "print1: " << i << endl;
cv.notify_all();
}
}
void print2()
{
unique_lock<mutex> ul(mtx);
while (true)
{
while (flag != 2)
{
cv.wait(ul);
}
flag = 0;
if (++ i > 100)
{
cv.notify_all();
break;
}
cout << "print2: " << i << endl;
cv.notify_all();
}
}
int main()
{
cout << "print 1 ~ 100" << endl;
thread a(print0);
thread b(print1);
thread c(print2);
a.join();
b.join();
c.join();
return 0;
}