• std::condition_variable(二)


    #include <iostream>                // std::cout
    #include <thread>                // std::thread, std::this_thread::yield
    #include <mutex>                // std::mutex, std::unique_lock
    #include <condition_variable>    // std::condition_variable
    
    std::mutex mtx;
    std::condition_variable cv;
    //通过cargo来判断有没有被消费
    int cargo = 0;
    bool shipment_available()
    {
        return cargo != 0;
    }
    
    // 消费者线程.
    void consume(int n)
    {
        for (int i = 0; i < n; ++i) {
            std::unique_lock <std::mutex> lck(mtx);
            cv.wait(lck, shipment_available);//第二个参数不知干什么的
            std::cout << cargo << '
    ';
            cargo = 0;
        }
    }
    
    int main()
    {
        std::thread consumer_thread(consume, 10); // 消费者线程.
    
        // 主线程为生产者线程, 生产 10 个物品.
        for (int i = 0; i < 10; ++i) {
    /*当
    consumer_thread时就有两条线,主和工作者线程,shipment_available正好可以判断子线程是否取走商品*/
    while (shipment_available())
                std::this_thread::yield();//估计类似sleep()
            std::unique_lock <std::mutex> lck(mtx);
            cargo = i + 1;
            cv.notify_one();//cargo有值通知阻塞的的线程运行
        }
    
        consumer_thread.join();
        getchar();
        return 0;
    }

    具体看http://www.cnblogs.com/haippy/p/3252041.html

  • 相关阅读:
    2019.04.19 坦克大战
    2019.04.18 异常和模块
    2019.04.17 面向对象编程篇207
    fork操作时的copy-on-write策略
    Redis阻塞原因
    Redis持久化-fork操作
    Redis持久化-AOF重写
    Redis持久化-aof
    Redis持久化
    Shopify给左右两边布局的banner图加链接,链接失败
  • 原文地址:https://www.cnblogs.com/zzyoucan/p/3673196.html
Copyright © 2020-2023  润新知