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;

}

结果

相关推荐
遇见你...5 分钟前
B02 SpringMVC的请求和相应
java·开发语言
Yu_Lijing7 分钟前
基于C++的《Head First设计模式》笔记——访问者模式
c++·笔记·设计模式
计算机安禾11 分钟前
【数据结构与算法】第20篇:二叉树的链式存储与四种遍历(前序、中序、后序、层序)
c语言·开发语言·数据结构·c++·学习·算法·visual studio
顶点多余12 分钟前
POSIX信号量+生产消费模型应用+环形缓冲区实现
linux·c++
_MyFavorite_16 分钟前
JAVA重点基础、进阶知识及易错点总结(17)线程安全 & synchronized 同步锁
java·开发语言·安全
_MyFavorite_17 分钟前
JAVA重点基础、进阶知识及易错点总结(13)File 类 + 路径操作
java·开发语言
不会写DN18 分钟前
如何使用PHP创建图像验证码
android·开发语言·php
禾小西29 分钟前
深入理解 Java String:从底层原理到高性能优化实战
java·开发语言·性能优化
￰meteor33 分钟前
【函数指针】
c++
Huangjin007_35 分钟前
【C++类和对象(四)】手撕 Date 类:赋值运算符重载 + 日期计算
开发语言·c++