1. 程式人生 > >高效能併發佇列(C++實現)

高效能併發佇列(C++實現)

注意:1、解構函式沒有加鎖,因為需要同時對head lock和tail lock加鎖。不建議在析構不確定的情況下使用。

2、經測試,比加鎖的std::list快50%,比加鎖的std::queue慢20%。

template <typename T>
class concurrent_queue
{
public:
	concurrent_queue()
	{
		NODE* node = new NODE();
		node->next = NULL;

		head_ = node;
		tail_ = node;
	}

	~concurrent_queue()
	{
		NODE* node = head_;

		do
		{
			node = erase_(node);
		}
		while(node != NULL);
	}

	void push(const T& val)
	{
		NODE* node = new NODE();
		node->val = val;
		node->next = NULL;

		scoped_lock lock(t_lock_);
		tail_->next = node;
		tail_ = node;
	}

	bool pop(T* val)
	{
		scoped_lock lock(h_lock_);
		if(empty_())
		{
			return false;
		}

		head_ = erase_(head_);
		*val = head_->val;
		return true;
	}

private:
	struct NODE
	{
		T val;
		NODE* next;
	};

private:
	bool empty_() const
	{
		return head_->next == NULL;
	}

	NODE* erase_(NODE* node) const
	{
		NODE* tmp = node->next;
		delete node;
		return tmp;
	}

private:
	NODE* head_;
	NODE* tail_;
	concurrent_lock h_lock_;
	concurrent_lock t_lock_;
};

class concurrent_lock
{
public:
	concurrent_lock()
	{
		InitializeCriticalSection(&cs_);
	}

	~concurrent_lock()
	{
		DeleteCriticalSection(&cs_);
	}

	void lock()
	{
		EnterCriticalSection(&cs_);
	}

	void unlock()
	{
		LeaveCriticalSection(&cs_);
	}

private:
	CRITICAL_SECTION cs_;
};

class scoped_lock
{
public:
	scoped_lock(const concurrent_lock& lock) : lock_(lock)
	{
		const_cast<concurrent_lock&>(lock_).lock();
	}

	~scoped_lock()
	{
		const_cast<concurrent_lock&>(lock_).unlock();
	}

private:
	const concurrent_lock& lock_;
};