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;

}

结果

相关推荐
ComputerInBook2 分钟前
C++编程语言:标准库:第39章——本地化(语言环境)( Locales)(Bjarne Stroustrup)
c++·c++语言环境·c++ 本地化设置·c++ locale·c++ facet·语言特征
hefaxiang6 分钟前
分支循环(下)(二)
c语言·开发语言·数据结构
黑客思维者42 分钟前
Python大规模数据处理OOM突围:从迭代器原理到TB级文件实战优化
开发语言·python·github·迭代器·oom
繁华似锦respect1 小时前
C++ 智能指针底层实现深度解析
linux·开发语言·c++·设计模式·代理模式
lkbhua莱克瓦241 小时前
IO流练习(加密和解密文件)
java·开发语言·笔记·学习方法·io流·io流练习题
偶像你挑的噻2 小时前
3.Qt-基础布局以及事件
开发语言·数据库·qt
CHANG_THE_WORLD2 小时前
Python 学习三 Python字符串拼接详解
开发语言·python·学习
诸葛老刘2 小时前
next.js 框架中的约定的特殊参数名称
开发语言·javascript·ecmascript
Bona Sun3 小时前
单片机手搓掌上游戏机(二十三)—esp32运行简单街机模拟器软硬件准备
c语言·c++·单片机
霸王大陆3 小时前
《零基础学 PHP:从入门到实战》模块十:从应用到精通——掌握PHP进阶技术与现代化开发实战-2
android·开发语言·php