C++三个线程依次打印abc

代码

cpp 复制代码
#include<iostream>
#include<thread>
#include<mutex>
#include<condition_variable>
using namespace std;
mutex mtx;
condition_variable cv;
int flag=0;
void A(){
    unique_lock<mutex>lk(mtx);
    int count=0;
    while(count<10){
        while(flag!=0) cv.wait(lk);
        cout<<"thread1 : a"<<endl;
        count++;
        this_thread::sleep_for(chrono::milliseconds(500));
        flag=1;
        cv.notify_all();
        
    }
    cout<<"thread 1 finish"<<endl;

}
void B(){
    unique_lock<mutex>lk(mtx);
    int count=0;
    while(count<10){
        while(flag!=1) cv.wait(lk);
        cout<<"thread 2 : b"<<endl;
        this_thread::sleep_for(chrono::milliseconds(500));
        flag=2;
        cv.notify_all();
        count++;
    }
    cout<<"thread 2 finished"<<endl;

}
void C(){
    unique_lock<mutex>lk(mtx);
    int count=0;
    while(count<10){
        while(flag!=2) cv.wait(lk);
        cout<<"thread 3 : c"<<endl;
        this_thread::sleep_for(chrono::milliseconds(500));
        flag=0;
        cv.notify_all();
        count++;
    }
    cout<<"thread 3 finished"<<endl;

}
int main(){
    thread t1(A);
    thread t2(B);
    thread t3(C);
    t1.join();
    t2.join();
    t3.join();
    return 0;

}

结果

相关推荐
灰子学技术17 小时前
go response.Body.close()导致连接异常处理
开发语言·后端·golang
二十雨辰17 小时前
[python]-AI大模型
开发语言·人工智能·python
Yvonne爱编码17 小时前
JAVA数据结构 DAY6-栈和队列
java·开发语言·数据结构·python
Re.不晚17 小时前
JAVA进阶之路——无奖问答挑战1
java·开发语言
你这个代码我看不懂17 小时前
@ConditionalOnProperty不直接使用松绑定规则
java·开发语言
pas13618 小时前
41-parse的实现原理&有限状态机
开发语言·前端·javascript
琹箐18 小时前
最大堆和最小堆 实现思路
java·开发语言·算法
Monly2118 小时前
Java:修改打包配置文件
java·开发语言
我命由我1234519 小时前
Android 广播 - 静态注册与动态注册对广播接收器实例创建的影响
android·java·开发语言·java-ee·android studio·android-studio·android runtime
island131419 小时前
CANN ops-nn 算子库深度解析:核心算子(如激活函数、归一化)的数值精度控制与内存高效实现
开发语言·人工智能·神经网络