C++11线程安全队列

本文详细介绍了如何利用C++11的并发特性,设计并实现一个线程安全的队列,讨论了互斥锁和条件变量在多线程环境中的应用,确保了队列操作的正确性和高效性。

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


多线程编程需要实现一个线程安全的队列,上锁,避免多个线程同时读写

代码:

/**
 * 线程安全的队列
 */

#ifndef __THREAD_SAFE_QUEUE__
#define __THREAD_SAFE_QUEUE__
#include <iostream>
#include <queue>
#include <mutex>
#include <condition_variable>

template <class T>
class thread_safe_queue
{
private:
	mutable mutex 		mut;		//锁
	queue<T> 			data_queue;	//队列
	condition_variable 	data_cond;	//条件变量
public:
	//构造函数
	thread_safe_queue();
	thread_safe_queue &operator=(const thread_safe_queue&)=delete;

	//可以多传递一个额外的条件
	bool wait_and_pop(T &value,atomic_bool &bl);
	bool try_pop(T &value);
	void push(T new_value);
	bool empty() const;

	void notify_all()
	{
		data_cond.notify_all();
	}
};
template <class T>
thread_safe_queue<T>::thread_safe_queue(){}

template <class T>
bool thread_safe_queue<T>::empty() const
{
	lock_guard<mutex> lock(mut);
	return data_queue.empty();
}

template <class T>
void thread_safe_queue<T>::push(T new_value)
{
	lock_guard<mutex> lock(mut);
	data_queue.push(new_value);
	data_cond.notify_one();
}


template <class T>
bool thread_safe_queue<T>::wait_and_pop(T &value,atomic_bool &bl)
{
	unique_lock<mutex> lock(mut);
	
	//避免队列为空时一直等待
	data_cond.wait(lock,[this,&bl](){return (!this->data_queue.empty())||bl; });

	if(bl&&data_queue.empty())
		return false;

	value=data_queue.front();
	data_queue.pop();
	return true;
}
template<class T>
bool thread_safe_queue<T>::try_pop(T &value)
{
	lock_guard<mutex> lock(mut);
	if(empty())
		return false;

	value=data_queue.front();
	data_queue.pop();
	return true;
}

#endif
对于mutex我的理解是在同一个mutex的lock、unlock之间的代码不能同时运行。
condition_variable:线程之间同步的一种方式,通过notify_one --> wait、ontify_all-->wait配合使用 
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值