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

本文介绍Boost库中的condition_variable组件及其在线程同步中的应用。通过一个具体的并发队列类实现示例,展示了如何利用condition_variable来通知等待线程数据变化的情况,从而实现生产者-消费者模式下的高效线程间通信。

摘要生成于 C知道 ,由 DeepSeek-R1 满血版支持, 前往体验 >

boost::condition_variable 用法:

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

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

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

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

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


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

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值