基于锁的线程安全队列实现

基于锁的线程安全队列实现,第1张

基于锁的线程安全队列实现
#pragma once
#include
#include
#include
template
class threadsafe_queue
{
	using namespace std;
private:
	struct node
	{
		std::shared_ptr data;
		std::unique_ptr next;
	};
	std::mutex mx_head;
	std::mutex mx_tail;
	std::unique_ptr head;
	node* tail;
	std::condition_variable data_cond;
public:
	//空队列是头尾指针都指向一个默认的节点
	threadsafe_queue() :head(new node), tail(head.get()) {}
	threadsafe_queue(const threadsafe_queue&) = delete;
	threadsafe_queue& operator =(const threadsafe_queue&) = delete;

	
	//出队列并获取出队的对头值
	std::shared_ptr try_pop();
	bool try_pop(T& value);

	std::shared_ptr wait_and_pop();
	void wait_and_pop(T& value);
	void push(T NewValue);
	void empty();

	//这里没有提供size 因为是并发数据结构 若要了解队列中元素个数 可以自己定义一个原子变量 push成功加1 pop成功减1

	
private:
	node*  get_tail()
	{
		std::lock_guard lk(mx_tail);
		return tail;
	}
	std::unique_ptr pop_head()
	{
		std::unique_ptr old_head = std::move(head);
		head = std::move(old_head->next);
		return old_head;
	}
	std::unique_ptr try_pop_head()
	{
		std::lock_guardheadlock(mx_head);
		if (head.get() == get_tail())
			return unique_ptr();
		return pop_head();
	}
	std::unique_ptr try_pop_head(T&value)
	{
		std::lock_guardheadlock(mx_head);
		if (head.get() == get_tail())
			return unique_ptr();
		value = std::move(*head->data);
		return pop_head();
	}
	std::unique_lock wait_for_data()
	{
		std::unique_lock headlock(mx_head);
		data_cond.wait(&headlock, [this]{ return head.get() != get_tail(); });
		return std::move(headlock);
	}
	std::unique_ptr wait_pop_head()
	{
		std::unique_lock headlock(wait_for_data());
		return pop_head();
	}
	std::unique_ptr wait_pop_head(T&value)
	{
		std::unique_lock headlock(wait_for_data());
		value = std::move(*head->data);
		return pop_head();
	}

};

template
inline std::shared_ptr threadsafe_queue::try_pop()
{
	 std::unique_ptrold_head=try_pop_head();
	 return old_head ? old_head->data : std::shared_ptr();
}

template
inline bool threadsafe_queue::try_pop(T& value)
{
	std::unique_ptrold_head = try_pop_head(value);
	return old_head;
}

template
inline std::shared_ptr threadsafe_queue::wait_and_pop()
{
	const std::unique_ptr old_head = wait_pop_head();
	return old_head->data;

}

template
inline void threadsafe_queue::wait_and_pop(T& value)
{
	const std::unique_ptr old_head = wait_pop_head(value);
}

template
inline void threadsafe_queue::push(T NewValue)
{
	std::shared_ptr data(std::make_shared(std::move(NewValue)));
	std::unique_ptr pNode = std::make_unique();

	{
		std::lock_guard lk(mx_tail);
		Node*const  Newtail = pNode.get();
		tail->data = data;
		tail->next = std::move(pNode);
		tail = Newtail;
	}
	data_cond.notify_one();
}

template
inline void threadsafe_queue::empty()
{
	std::lock_guardheadlock(mx_head);
	return (head.get() == get_tail());
}

欢迎分享,转载请注明来源:内存溢出

原文地址: http://outofmemory.cn/zaji/5659357.html

(0)
打赏 微信扫一扫 微信扫一扫 支付宝扫一扫 支付宝扫一扫
上一篇 2022-12-16
下一篇 2022-12-16

发表评论

登录后才能评论

评论列表(0条)

保存