c++ 多线程 互锁 条件变量

cpp 复制代码
#include <iostream>
#include <thread>
#include <mutex>
#include <condition_variable>
#include <chrono>
using namespace std;

mutex mtx;
condition_variable cv;
bool ready = false;

void thread_A(int id)
{
    unique_lock<mutex> lck(mtx);
   
    cv.wait(lck); // 等待条件变量 ,线程被挂起
    cout << "Thread " << id << " is waitting\n";
    while (!ready) int m=1; /*cv.wait(lck);*/ // 等待条件变量
    cout << "Thread " << id << " is running\n";
}

void thread_B()
{
    cout << "Initializing...\n";
    this_thread::sleep_for(chrono::milliseconds(2000)); // 模拟初始化过程
    {
        {
         lock_guard<mutex> lck(mtx); // 自动加锁互斥量
         ready = true; // 设置条件变量     
        }
        cout << "Initialization complete\n";
    
        cv.notify_all();  // 唤醒所有等待的线程
        this_thread::sleep_for(chrono::milliseconds(2000)); // 模拟初始化过程
        cout << "All thread Initialization complete\n";
    }
  /*  this_thread::sleep_for(chrono::milliseconds(2000));
    cout << "Initialization complete2\n";*/
   
}

int main()
{
    
    thread t1(thread_A, 1);
    thread t2(thread_A, 2);
    thread t3(thread_A, 3);
    thread t4(thread_B);
   
    t1.join();
    t2.join();
    t3.join();
    t4.join();
}

运行结果:

cpp 复制代码
Initializing...
Initialization complete
Thread 2 is waitting
Thread 2 is running
Thread 1 is waitting
Thread 1 is running
Thread 3 is waitting
Thread 3 is running
All thread Initialization complete
相关推荐
多读书1939 分钟前
Java多线程进阶-深入synchronized与CAS
java·开发语言·java-ee
汤永红24 分钟前
week1-[分支结构]中位数
c++·算法·信睡奥赛
啊阿狸不会拉杆27 分钟前
《算法导论》第 24 章 - 单源最短路径
开发语言·数据结构·c++·算法·php
衍余未了28 分钟前
Centos9傻瓜式linux部署CRMEB 开源商城系统(PHP)
开发语言·php
xzkyd outpaper1 小时前
Kotlin 协程启动方式
android·开发语言·kotlin
集成显卡1 小时前
在JVM跑JavaScript脚本 | 简单 FaaS 架构设计与实现
开发语言·javascript·jvm·设计模式·kotlin·软件开发·faas
数据熊猫Taobaoapi20141 小时前
JavaScript 实现模块懒加载的几种方式
开发语言·javascript·ecmascript
Swift社区2 小时前
Swift 实战:从数据流到不重叠区间的高效转换
开发语言·ios·swift
点云侠2 小时前
【2025最新版】PCL点云处理算法汇总(C++长期更新版)
c++·算法·计算机视觉·3d·可视化
码农阿豪2 小时前
飞算JavaAI:专为Java开发者打造的智能编程革命
java·开发语言·microsoft