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
相关推荐
y1su1 分钟前
Leetcode 单调栈模板
java·开发语言·数据结构·算法·leetcode
2601_962885727 分钟前
如何用 Python 计算索提诺比率和卡玛比率?
开发语言·python
郑州光合科技余经理14 分钟前
出海外卖平台:支付对接为什么要和下单收款分开
android·java·开发语言·前端·后端·php·ai编程
kimnoic21 分钟前
Python操作MySQL数据库的两种方式实例分析【pymysql和pandas】
开发语言·python
苏辰澈24 分钟前
C++独属于自己的变身:多态
c语言·开发语言·c++·visualstudio·编辑器
谢亮_vipxieliang24 分钟前
PHP 异常处理全解析:try-catch、自定义异常与全局异常处理器
开发语言·php
外收内放27 分钟前
Python基础语法练习题(65)
开发语言·python
水饺编程28 分钟前
第1章,[Win32 章节]:在 VS2019 里面安装 MSDN
c语言·c++·windows·visual studio
垆边人似月.30 分钟前
华为题:每日温度
数据结构·c++·算法
浅尝辄止;33 分钟前
设计模式在HIS/LIS医疗系统中的完整实践指南(C#版)
开发语言·设计模式·c#