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();  
    }  
};

  

posted on 2012-08-09 11:11  110440  阅读(10546)  评论(0编辑  收藏  举报

导航