c++11 线程池系列之一 所需要的thread_safe_queue

这是一个C++11实现的线程安全队列`thread_safe_queue`,用于线程池。队列使用了互斥锁`mutex`,条件变量`condition_variable`以及智能指针`shared_ptr`来保证多线程环境中的安全操作。提供了`push`、`wait_and_pop`、`try_pop`等方法,方便在线程池中进行数据入队和出队。
摘要由CSDN通过智能技术生成
template<class T>
class thread_safe_queue
{
private:
	mutable std::mutex mut;
	std::queue<std::shared_ptr<T>> data_queue;
	std::condition_variable data_con;
public:
	thread_safe_queue(){}
	thread_safe_queue(thread_safe_queue const& other)
	{
	std::lock_guard<std::mutex> lk(other.mut);
	data_queue = other.data_queue;
	}
	void push(T tValue)
	{
		std::shared_ptr<T> data(std::make_shared<T>(std::move(tValue)));
	std::lock_guard<std::mutex> lk(mut);
	data_queue.push(data);
	data_con.notify_one();
	}
	void wait_and_pop(T& tValue)
	{
	std::unique_lock<std::mutex> lk(mut);
	data_con.wait(lk,[this]{return !data_queue.empty();});
	tValue = std::move(*data_queue.front());
	data_queue.pop();
	}
	std::shared_ptr<T>wait_and_pop()
	{
	std::unique_lock<std::mutex> lk(mut);
	data_con.wait(lk,[this]{return !data_queue.empty();});
	std::shared_ptr<T> ret (std::make_shared<T>(data_queue
  • 3
    点赞
  • 4
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值