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;

}

结果

相关推荐
jimy17 小时前
c++的 Type Traits (一)
开发语言·c++
别动我齐刘海8 小时前
Linux 系统调试学习2
linux·运维·c++·人工智能·学习·机器学习·机器人
Web极客码8 小时前
Python Ollama 本地 Agent 入门与订单查询实践
开发语言·jvm·python
kimnoic8 小时前
PHP 8.2的DNF类型怎么用才规范
开发语言·php
_Evan_Yao9 小时前
前后端联调怎么排查问题?从 Network 到后端日志,一步步定位错误
开发语言·后端·团队开发·需求分析
hudd6689 小时前
JavaEE 初阶 - 多线程(进阶)
java·开发语言·java-ee
小白快快跑哦9 小时前
python-字符串全解(六):正则表达式-前后相断言
开发语言·python·正则表达式·前后相断言
ZZHow10249 小时前
Ascend C算子开发(高级)笔记
c++·人工智能·笔记·深度学习·华为云
kimnoic9 小时前
Python数据分析中正则表达式匹配字符串与常用函数示例详解
开发语言·python
中屹指纹浏览器svip9 小时前
打开账号环境网页报错,常见原因有哪些?
服务器·开发语言·php·中屹指纹浏览器