• Linux c++ 试验-1 条件变量(condition_variable)


    1、示例

    #include <iostream> // std::cout
    
    #include <thread> // std::thread
    
    #include <mutex> // std::mutex, std::unique_lock
    
    #include <condition_variable> // std::condition_variable
    
    std::mutex mtx; // 全局互斥锁.
    
    std::condition_variable cv; // 全局条件变量.
    
    bool ready = false; // 全局标志位.
    
    void do_print_id(int id)
    
    {
    
        std::unique_lock<std::mutex> lck(mtx);
    
        while (!ready) // 如果标志位不为 true, 则等待...
    
            cv.wait(lck); // 当前线程被阻塞, 当全局标志位变为 true 之后,
    
        // 线程被唤醒, 继续往下执行打印线程编号id.
    
        std::cout << "thread " << id << '
    ';
    }
    
    void go()
    
    {
    
        std::unique_lock<std::mutex> lck(mtx);
    
        ready = true; // 设置全局标志位为 true.
    
        cv.notify_all(); // 唤醒所有线程.
    }
    
    int main()
    
    {
    
        std::thread threads[10];
    
        // spawn 10 threads:
    
        for (int i = 0; i < 10; ++i)
    
            threads[i] = std::thread(do_print_id, i);
    
        std::cout << "10 threads ready to race...
    ";
    
        go(); // go!
    
        for (auto &th : threads)
    
            th.join();
    
        return 0;
    }
    

    2、编译
    g++ ./testcondition_variable.cpp -lpthread
    3、运行结果
    10 threads ready to race...
    thread 7
    thread 3
    thread 2
    thread 4
    thread 1
    thread 0
    thread 5
    thread 6
    thread 9
    thread 8

    本博客是个人工作中记录,遇到问题可以互相探讨,没有遇到的问题可能没有时间去特意研究,勿扰。
    另外建了几个QQ技术群:
    2、全栈技术群:616945527,加群口令abc123
    2、硬件嵌入式开发: 75764412
    3、Go语言交流群:9924600

    闲置域名www.nsxz.com出售(等宽等高字符四字域名)。
  • 相关阅读:
    高负载的Lamp架构 转自:http://www.litrin.net/2011/04/20/%E9%AB%98%E8%B4%9F%E8%BD%BD%E7%9A%84lamp%E6%9E%B6%E6%9E%84/
    面向对象设计的基本原则
    [Tip: bat] About "%~dp0"
    [Tip: c# override]
    Where partial types fit in
    Further Overrideable things besides Methods
    [Tip]单位换算
    重构代码解决问题的基本思路
    随想编程之道
    VS快捷键
  • 原文地址:https://www.cnblogs.com/zhaogaojian/p/15360344.html
Copyright © 2020-2023  润新知