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
相关推荐
m0_73812072几秒前
CTFshow系列——PHP特性Web93-96
开发语言·安全·web安全·php·ctfshow
ulias2121 分钟前
各种背包问题简述
数据结构·c++·算法·动态规划
m0_5704664111 分钟前
代码随想录算法训练营第二十八天 | 买卖股票的最佳实际、跳跃游戏、K次取反后最大化的数组和
java·开发语言·算法
程序喵大人12 分钟前
分享个C++线程池的实现源码
开发语言·c++·线程池
不会吃萝卜的兔子36 分钟前
go webrtc - 1 go基本概念
开发语言·golang·webrtc
FL162386312943 分钟前
[ubuntu][C++]onnxruntime安装cpu版本后测试代码
linux·c++·ubuntu
要做朋鱼燕1 小时前
【C++】 priority_queue 容器模拟实现解析
开发语言·c++·笔记·职场和发展
jiaway1 小时前
【C语言】第四课 指针与内存管理
c语言·开发语言·算法
励志不掉头发的内向程序员1 小时前
C++进阶——继承 (1)
开发语言·c++·学习
mit6.8243 小时前
并查集|栈
c++