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
相关推荐
航哥的女人5 分钟前
setsockopt()详解
c++·tcp/ip
阿猿收手吧!15 分钟前
【Linux/C++】线程切换与协程切换,协程池
linux·c++
百锦再26 分钟前
Java synchronized关键字详解:从入门到原理(两课时)
java·开发语言·struts·spring·kafka·tomcat·maven
油丶酸萝卜别吃31 分钟前
什么是 Java 内存模型(JMM)?
java·开发语言
量子炒饭大师1 小时前
【C++入门】Cyber神经的义体插件 —— 【类与对象】内部类
java·开发语言·c++·内部类·嵌套类
Hx_Ma161 小时前
测试题(四)
java·开发语言·jvm
xiaoye-duck1 小时前
C++ 模板进阶:从非类型参数、特化到分离编译,吃透 C++ 泛型编程的核心逻辑
c++·面试·模板
多打代码1 小时前
2026.02.11
开发语言·python
lly2024061 小时前
Scala IF...ELSE 语句详解
开发语言
不吃鱼的猫7481 小时前
【ffplay 源码解析系列】02-核心数据结构详解
c++·ffmpeg·音视频