zoukankan      html  css  js  c++  java
  • boost::condition_variable 设计c++ 生产者消费者队列

    boost::condition_variable 用法:

    当线程间的共享数据发生变化的时候,可以通过condition_variable来通知其他的线程。消费者wait 直到生产者通知其状态发生改变,Condition_variable是使用方法如下:

    ·当持有锁之后,线程调用wait

    ·wait解开持有的互斥锁(mutex),阻塞本线程,并将自己加入到唤醒队列中

    ·当收到通知(notification),该线程从阻塞中恢复,并加入互斥锁队列(mutex queue)

     线程被唤醒之后继续持有锁运行。

    以下一个例子转自:

    http://www.justsoftwaresolutions.co.uk/threading/implementing-a-thread-safe-queue-using-condition-variables.html

    template<typename Data>  
    class concurrent_queue  
    {  
    private:  
        std::queue<Data> the_queue;  
        mutable boost::mutex the_mutex;  
        boost::condition_variable the_condition_variable;  
    public:  
        void push(Data const& data)  
        {  
            boost::mutex::scoped_lock lock(the_mutex);  
            the_queue.push(data);  
            lock.unlock();  
            the_condition_variable.notify_one();  
        }  
        bool empty() const  
        {  
            boost::mutex::scoped_lock lock(the_mutex);  
            return the_queue.empty();  
        }  
        bool try_pop(Data& popped_value)  
        {  
            boost::mutex::scoped_lock lock(the_mutex);  
            if(the_queue.empty())  
            {  
                return false;  
            }  
              
            popped_value=the_queue.front();  
            the_queue.pop();  
            return true;  
        }  
        void wait_and_pop(Data& popped_value)  
        {  
            boost::mutex::scoped_lock lock(the_mutex);  
            while(the_queue.empty())  
            {  
                the_condition_variable.wait(lock);  
            }  
              
            popped_value=the_queue.front();  
            the_queue.pop();  
        }  
    };
    

      

  • 相关阅读:
    将数据绑定通过图表显现
    d3.js初识
    Josn
    d3-tip.js
    Java知识点总结
    Javascript的学习
    Java的多线程学习
    day11
    day10
    day09
  • 原文地址:https://www.cnblogs.com/sanjin/p/2629890.html
Copyright © 2011-2022 走看看