boost::condition_variable 设计c++ 生产者消费者队列

http://www.cnblogs.com/sanjin/archive/2012/08/09/2629890.html


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

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值