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;

}

结果

相关推荐
A_nanda10 分钟前
c#WPF开发常见问题
开发语言·c#·wpf
Hello.Reader25 分钟前
REALITY 技术深度解析从 TLS 伪装、抗主动探测到 VLESS + XTLS Vision 完整实践
开发语言·php
不正经学生33 分钟前
C语言字符串函数进阶:安全版函数 + 错误处理 + 子串查找
c语言·开发语言·c++·算法·面试
ITKEY_1 小时前
neovim基于nvim-jdtls 开发java报错
java·开发语言
無限進步D1 小时前
Java 代码块
java·开发语言
吃好睡好便好1 小时前
MATLAB仿真框图4
开发语言·matlab·仿真·分段函数
三克的油1 小时前
算法基础-1
数据结构·c++·算法
TheBestRucy1 小时前
基于Dify的旅游攻略&王者荣耀攻略智能助手项目
服务器·开发语言·人工智能·python·算法·旅游
一水1 小时前
Pi :内置四工具源码拆解——文件锁、变更快照与 bash 隔离
开发语言·chrome·ai·bash
梅菲塔亚1 小时前
Keepalived高可用全解析
linux·运维·服务器·开发语言·网络·php