zoukankan      html  css  js  c++  java
  • std::condition_variable(复习)

    #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; // 全局标志位.
    
    //1.当一个线程进入时会上锁,然后调用wait会使线程阻塞,然后会解锁
    //2.当解锁之后其他线程就可以获得锁,所以所有的线程都会阻塞
    //3.notify的时候wait会上锁
    //看来这锁和wait操作一起使用可以很好的保证线程的安全,在notif之前能保证只有一个线程访问,在notif之后也能保证只有一个线程访问
    
    void do_print_id(int id)
    {
        std::unique_lock <std::mutex> lck(mtx);
        while (!ready) 
            cv.wait(lck);
        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();
        getchar();
        return 0;
    }
  • 相关阅读:
    类的加载顺序
    自定义形状类
    java的参数传递
    复数相加+equels、hashcode、clone<二>
    复数相加+equels、hashcode、clone<一>
    命令行程序
    计算阶乘
    控制程序的流程
    java运算符
    强制类型转换细节解析
  • 原文地址:https://www.cnblogs.com/zzyoucan/p/3826762.html
Copyright © 2011-2022 走看看