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;

}

结果

相关推荐
ZouZou老师42 分钟前
C++设计模式之装饰器模式:以家具生产为例
c++·设计模式·装饰器模式
ZouZou老师1 小时前
C++设计模式之桥接模式:以家具生产为例
c++·设计模式·桥接模式
diegoXie1 小时前
Python / R 向量顺序分割与跨步分割
开发语言·python·r语言
程序员小白条1 小时前
0经验如何找实习?
java·开发语言·数据结构·数据库·链表
呱呱巨基1 小时前
Linux 进程概念
linux·c++·笔记·学习
liulilittle1 小时前
C++ 浮点数封装。
linux·服务器·开发语言·前端·网络·数据库·c++
ZouZou老师1 小时前
C++设计模式之组合模式:以家具生产为例
c++·设计模式·组合模式
yong15858553431 小时前
2. Linux C++ muduo 库学习——原子变量操作头文件
linux·c++·学习
失散132 小时前
Python——1 概述
开发语言·python
萧鼎2 小时前
Python 图像哈希库 imagehash——从原理到实践
开发语言·python·哈希算法