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;

}

结果

相关推荐
o独酌o9 分钟前
递归的‘浅’理解
java·开发语言
Book_熬夜!12 分钟前
Python基础(六)——PyEcharts数据可视化初级版
开发语言·python·信息可视化·echarts·数据可视化
m0_6312704039 分钟前
高级c语言(五)
c语言·开发语言
Lenyiin41 分钟前
《 C++ 修炼全景指南:十 》自平衡的艺术:深入了解 AVL 树的核心原理与实现
数据结构·c++·stl
2401_858286111 小时前
53.【C语言】 字符函数和字符串函数(strcmp函数)
c语言·开发语言
程序猿练习生1 小时前
C++速通LeetCode中等第5题-无重复字符的最长字串
开发语言·c++·leetcode
2401_858120261 小时前
MATLAB中的无线通信系统部署和优化工具有哪些
开发语言·matlab
MATLAB滤波1 小时前
【PSINS】基于PSINS工具箱的EKF+UKF对比程序|三维定位|组合导航|MATLAB
开发语言·matlab
2401_858120531 小时前
MATLAB在嵌入式系统设计中的最佳实践
开发语言·matlab
蓝裕安1 小时前
伪工厂模式制造敌人
开发语言·unity·游戏引擎