C++线程安全队列

这是一个模板类`concurrent_queue`,用于创建线程安全的队列。队列内部使用了`std::queue`,并通过`boost::mutex`和`boost::condition_variable`来确保线程安全。提供了`push`、`empty`、`try_pop`和`wait_and_pop`等方法,其中`push`方法利用锁和条件变量通知生产者线程,`try_pop`和`wait_and_pop`则允许消费者线程安全地从队列中取出元素。
摘要由CSDN通过智能技术生成
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)
    {
#if 0
        boost::mutex::scoped_lock lock(the_mutex);
        the_queue.push(data);
        lock.unlock();
#else   //利用作用域自动释放锁,防止异常崩溃场景
        {
            boost::mutex::scoped_lock lock(the_mutex);
            the_queue.push(data);
        }
#endif
        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();
  • 1
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值