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
相关推荐
流星白龙3 分钟前
【Qt】7.信号和槽_connect函数用法(1)
开发语言·数据库·qt
小龙报19 分钟前
《算法通关指南---C++编程篇(1)》
开发语言·c++·程序人生·算法·学习方法·visual studio
Cx330❀28 分钟前
《C++ 手搓list容器底层》:从结构原理深度解析到功能实现(附源码版)
开发语言·数据结构·c++·经验分享·算法·list
仰泳的熊猫1 小时前
LeetCode:98. 验证二叉搜索树
数据结构·c++·算法·leetcode
暴力求解1 小时前
C++ --- 模版初阶
c++
CC.GG1 小时前
【C++】STL容器--list的使用
开发语言·c++·list
洲覆1 小时前
基于 clangd 搭建 Redis 6.2 源码阅读与调试环境
开发语言·数据库·redis·缓存
草莓熊Lotso1 小时前
《算法闯关指南:优选算法--二分查找》--19.x的平方根,20.搜索插入位置
java·开发语言·c++·算法
旭意1 小时前
C++蓝桥杯之函数与递归
开发语言·c++·蓝桥杯
。TAT。1 小时前
C++ - vector
开发语言·c++·学习