#include <iostream>
#include <thread>
#include <mutex>
#include <condition_variable>
using namespace std;
mutex mymutex;
condition_variable cv;
int flag = 0;
void func_a() {
unique_lock<mutex> locka(mymutex);
for (int i = 0; i < 5; i++) {
while (flag != 0) cv.wait(locka);
cout << "thread1: A" << endl;
flag = 1;
cv.notify_all();
}
cout << "thread1 finsh" << endl;
}
void func_b() {
unique_lock<mutex> lockb(mymutex);
for (int i = 0; i < 5; i++) {
while (flag != 1) cv.wait(lockb);
cout << "thread2: B" << endl;
flag = 2;
cv.notify_all();
}
cout << "thread2 finsh" << endl;
}
void func_c() {
unique_lock<mutex> lockc(mymutex);
for (int i = 0; i < 5; i++) {
while (flag != 2) cv.wait(lockc);
cout << "thread3: C" << endl;
flag = 0;
cv.notify_all();
}
cout << "thread2 finsh" << endl;
}
int main() {
thread th1(func_a);
thread th2(func_b);
thread th3(func_c);
th1.join();
th2.join();
th3.join();
return 0;
}
|