#include <iostream>
#include <thread>
#include <mutex>
#include <condition_variable>
using namespace std;
#define PRINT_TIME 30
mutex mtx;
condition_variable cv;
int flag = 0;
void printA()
{
unique_lock<mutex> lk(mtx);
for(int i = 0; i < PRINT_TIME; ++i){
while(flag != 0) cv.wait(lk);
cout << "thread 1: a" << endl;
flag = 1;
cv.notify_all();
}
cout << "thread 1 finish" << endl;
}
void printB()
{
unique_lock<mutex> lk(mtx);
for(int i = 0; i < PRINT_TIME; ++i){
while(flag != 1) cv.wait(lk);
cout << "thread 2: b" << endl;
flag = 2;
cv.notify_all();
}
cout << "thread 2 finish" << endl;
}
void printC()
{
unique_lock<mutex> lk(mtx);
for(int i = 0; i < PRINT_TIME; ++i){
while(flag != 2) cv.wait(lk);
cout << "thread 3: c" << endl;
flag = 0;
cv.notify_all();
}
cout << "thread 3 finish" << endl;
}
int main()
{
thread th1(printB);
thread th2(printA);
thread th3(printC);
th1.join();
th2.join();
th3.join();
cout << "main finish" << endl;
return 0;
}
|