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;
    }
  • 相关阅读:
    Unity Ioc框架简单例子
    Newtonsoft.Json.Linq
    Quartz.net
    AngularJS
    Zookeeper
    mysql 游标CURSOR
    mysql 存储过程 CONCAT 字符串拼接
    MD5Util
    生成缩略图
    Asp.net MVC 基于Area的路由映射
  • 原文地址:https://www.cnblogs.com/zzyoucan/p/3826762.html
Copyright © 2011-2022 走看看