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();
C++线程安全队列
最新推荐文章于 2024-08-07 13:59:29 发布
这是一个模板类`concurrent_queue`,用于创建线程安全的队列。队列内部使用了`std::queue`,并通过`boost::mutex`和`boost::condition_variable`来确保线程安全。提供了`push`、`empty`、`try_pop`和`wait_and_pop`等方法,其中`push`方法利用锁和条件变量通知生产者线程,`try_pop`和`wait_and_pop`则允许消费者线程安全地从队列中取出元素。
摘要由CSDN通过智能技术生成