#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){
// condition_variable 对象通常使用 std::unique_lock 来等待
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;
}
按序打印ABC(c++实现)
最新推荐文章于 2022-10-07 15:41:35 发布
该博客展示了如何在C++中利用互斥锁(mutex)和条件变量(condition_variable)实现多线程间的同步与通信。通过三个线程printA、printB和printC交替打印字母,演示了条件变量在等待和通知机制中的应用,确保打印顺序的正确性。
摘要由CSDN通过智能技术生成