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
相关推荐
qwertyuiop_i1 分钟前
pe文件结构(TLS)
c++·tls·pe文件结构
chicpopoo5 分钟前
Python打卡DAY46
开发语言·python
灏瀚星空7 分钟前
Python数学可视化:3D参数曲面与隐式曲面绘制技术
开发语言·python·3d
Java Fans25 分钟前
如何在Windows本机安装Python并确保与Python.NET兼容
开发语言·windows·python
岁忧38 分钟前
(nice!!!)(LeetCode每日一题)2434. 使用机器人打印字典序最小的字符串(贪心+栈)
java·c++·算法·leetcode·职场和发展·go
无敌的小笼包1 小时前
第四讲:类和对象(下)
数据结构·c++
爱吃土豆的马铃薯ㅤㅤㅤㅤㅤㅤㅤㅤㅤ1 小时前
saveOrUpdate 有个缺点,不会把值赋值为null,解决办法
java·开发语言
Eiceblue1 小时前
C# 快速检测 PDF 是否加密,并验证正确密码
开发语言·pdf·c#·visual studio
FL16238631291 小时前
C#报错 iText.Kernel.Exceptions.PdfException: ‘Unknown PdfException
开发语言·c#
鑫鑫向栄1 小时前
[蓝桥杯]解谜游戏
数据结构·c++·算法·职场和发展·蓝桥杯