zoukankan      html  css  js  c++  java
  • 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出售(等宽等高字符四字域名)。
  • 相关阅读:
    CF251D
    P6914
    CF1100F
    双连通 / 圆方树 胡扯笔记
    P4082
    SparkSql使用Hive中注册的UDF函数报类找不到问题解决
    Oracle 查询时使用时间作为where报错hour must be between 1 and 12
    【面试-python】
    Linux和Git
    AMBA初探
  • 原文地址:https://www.cnblogs.com/zhaogaojian/p/15360344.html
Copyright © 2011-2022 走看看