3个线程轮流打印ABC
作者:
贺谦
,
2021-09-07 12:05:20
,
所有人可见
,
阅读 429
#include <iostream>
#include <thread>
#include <mutex>
using namespace std;
mutex mtx;
int flag = 0;
condition_variable cv;
void printA()
{
unique_lock<mutex> ul(mtx);
int cntA = 0;
while (cntA < 10)
{
while (flag != 0)
{
cv.wait(ul);
}
cout << "print A " << cntA + 1 << " times" << endl;
flag = 1;
cntA ++;
cv.notify_all();
}
}
void printB()
{
unique_lock<mutex> ul(mtx);
int cntB = 0;
while (cntB < 10)
{
while (flag != 1)
{
cv.wait(ul);
}
cout << "print B " << cntB + 1 << " times" << endl;
flag = 2;
cntB ++;
cv.notify_all();
}
}
void printC()
{
unique_lock<mutex> ul(mtx);
int cntC = 0;
while (cntC < 10)
{
while (flag != 2)
{
cv.wait(ul);
}
cout << "print C " << cntC + 1 << " times" << endl;
flag = 0;
cntC ++;
cv.notify_all();
}
}
int main()
{
thread a(printA);
thread b(printB);
thread c(printC);
a.join();
b.join();
c.join();
return 0;
}
请问有原题目链接吗?