C++11線程安全隊列


多線程編程需要實現一個線程安全的隊列,上鎖,避免多個線程同時讀寫

代碼:

/**
 * 線程安全的隊列
 */

#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配合使用 
發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章