zoukankan      html  css  js  c++  java
  • C++基础-多线程循环打印结果unique_lock<mutex>ulk(m)(设定锁定) cv.wait(ulk)(设置等待) cv.notify_all(通知全部)

    第一步: 设置unique_lock<mutex> ulk(m) //设定锁定

    第二步: 每一个线程在循环中等待, cv.wait(ulk) //不是该出现的场合等着

    第三步: cv.notify_all() //通知其他的线程,进行执行

    //
    // Created by Administrator on 2021/7/2.
    //
    #include<iostream>
    #include<thread>
    #include<mutex>
    #include<condition_variable>
    
    using namespace std;
    int LOOP = 10;
    int flag = 0;
    mutex m;
    condition_variable cv;
    
    //012012012
    void fun(int id)
    {
        for(int i = 0; i < LOOP; i++)
        {
            unique_lock<mutex> ulk(m); //设定锁定
            while((id - 65) != flag)
            {
                cv.wait(ulk); //不是该出现的场合等着
            }
            cout << (char)id << endl; //转换
            flag = (flag + 1) % 4; //
            cv.notify_all(); //通知全部
        }
    }
    int main()
    {
        thread t1(fun, 65);
        thread t2(fun, 66);
        thread t3(fun, 67);
        thread t4(fun, 68);
        t1.join();
        t2.join();
        t3.join();
        t4.join();
    }
  • 相关阅读:
    Android(一)
    git
    UBuntu18.04 配置环境
    TensorRT Development document (Python)
    继续
    tensorRT C++ API
    tensorRT 与yolov3_tiny
    浅谈PHP进程管理
    nginx 平滑重启的实现方法
    fast-cgi & php-fpm 等的理解 (讨论试理解)
  • 原文地址:https://www.cnblogs.com/my-love-is-python/p/14966183.html
Copyright © 2011-2022 走看看