C++基础-多线程通信(加锁)unique_lock<mutex>lck(m)(解锁)lock_guard<mutex>lckg(m)

线程间的通信

mutex m 定义互斥线程, condition_variable cv; //定义线程通信 

unqiue_lock<mutex>lck(m); //锁定  lock_guard<mutex>lckg(m); //解锁

cv.wait_for(lck, chrono::hours(1000)) //线程等待时间  cv.notify_all() //通知所有线程打开

完整代码

//
// Created by Administrator on 2021/6/27.
//
#include<thread>
#include<iostream>
#include<mutex>
#include<condition_variable>

using namespace std;
//线程通常,结合mutex
//一个线程, 多个线程处于等待, 通知一个或者通知多个
mutex m; //线程互相排斥
condition_variable cv; //线程通信
int main()
{
    auto **th = new thread *[10]; //开辟线程指针数组
    for(int i = 0; i < 10; ++i)
    {
        th[i] = new thread([](int index){
            unique_lock<mutex>lck(m); //锁定
            cv.wait_for(lck, chrono::hours(1000));
            cout << index << endl; //打印编号
        }, i); //传递参数
        this_thread::sleep_for(chrono::milliseconds(100)); //错开
    }

//    for(int i = 0; i < 10; i++)
//    {
//        lock_guard<mutex>lckg(m); //解锁的向导
//        cv.notify_one(); //挨个挨个通知
//    }
    for(int i = 0; i < 10; i++)
    {
        lock_guard<mutex>lckg(m);
    }
    cv.notify_all();
//    {
//        lock_guard<mutex> lckg(m);
//        cv.notify_all();
//    }
    for(int i = 0; i < 10; ++i)
    {
        th[i]->join();
        delete th[i];
    }
    delete[] th;
    cin.get();
}
原文地址:https://www.cnblogs.com/my-love-is-python/p/14940900.html