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
相关推荐
AC赳赳老秦10 分钟前
政务数据处理:DeepSeek 适配国产化环境的统计分析与报告生成
开发语言·hadoop·spring boot·postgresql·测试用例·政务·deepseek
xlxxy_39 分钟前
abap 批量创建供应商
运维·开发语言·sap·abap·pp·mm
GetcharZp1 小时前
拒绝硬编码!C++ 配置文件管理神器 yaml-cpp 实战指南
c++
独自破碎E1 小时前
Java是怎么实现跨平台的?
java·开发语言
墨有6661 小时前
C++ string 部分功能详解:迭代器、初始化与常用函数
开发语言·c++
Evand J1 小时前
【MATLAB例程】三维环境下,EKF融合INS与DVL的核心程序,用于惯导和速度传感器的数据融合滤波。附下载链接
开发语言·matlab
枫叶丹41 小时前
【Qt开发】Qt系统(二)-> 事件分发器
c语言·开发语言·数据库·c++·qt·系统架构
独自破碎E2 小时前
Leetcode1438绝对值不超过限制的最长连续子数组
java·开发语言·算法
澜莲花2 小时前
python图色之opencv基础---验证码实战
开发语言·python·opencv
沐知全栈开发2 小时前
Numpy 数组操作
开发语言