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
相关推荐
软件黑马王子2 小时前
C#初级教程(4)——流程控制:从基础到实践
开发语言·c#
闲猫2 小时前
go orm GORM
开发语言·后端·golang
黑不溜秋的3 小时前
C++ 设计模式 - 策略模式
c++·设计模式·策略模式
李白同学3 小时前
【C语言】结构体内存对齐问题
c语言·开发语言
黑子哥呢?4 小时前
安装Bash completion解决tab不能补全问题
开发语言·bash
青龙小码农4 小时前
yum报错:bash: /usr/bin/yum: /usr/bin/python: 坏的解释器:没有那个文件或目录
开发语言·python·bash·liunx
大数据追光猿5 小时前
Python应用算法之贪心算法理解和实践
大数据·开发语言·人工智能·python·深度学习·算法·贪心算法
Dream it possible!5 小时前
LeetCode 热题 100_在排序数组中查找元素的第一个和最后一个位置(65_34_中等_C++)(二分查找)(一次二分查找+挨个搜索;两次二分查找)
c++·算法·leetcode
柠石榴5 小时前
【练习】【回溯No.1】力扣 77. 组合
c++·算法·leetcode·回溯
王老师青少年编程5 小时前
【GESP C++八级考试考点详细解读】
数据结构·c++·算法·gesp·csp·信奥赛