zoukankan      html  css  js  c++  java
  • 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();
    }
  • 相关阅读:
    2017《Java技术》预备作业 计科1501 杨欣蕊
    Java技术预备作业02杨欣蕊
    系统无法从光盘启动
    动态数组ArrayList的使用
    dbgrid数据显示和数据源不同
    异步任务判断服务器是否开启
    Java字符串格式化
    思科2960 监听端口设置
    64位win7安装jdk和eclipse
    Delphi临界区的使用
  • 原文地址:https://www.cnblogs.com/my-love-is-python/p/14940900.html
Copyright © 2011-2022 走看看