一个简单好用的不加锁队列,用于单线程单次读取队列元素

//类

.h

#ifndef LOCK_FREE_QUEUE_H_
#define LOCK_FREE_QUEUE_H_

//不加锁队列,适合一个线程读取,一个线程写
#include <list>

using namespace std ;

template <typename T>
class CLockFreeQueue
{
public:
	CLockFreeQueue()
	{
		list.push_back(T());//分割节点
		iHead = list.begin();
		iTail = list.end();
	};

	void Produce(const T& t)//存消息
	{
		list.push_back(t);
		iTail = list.end();
		list.erase(list.begin(), iHead);
	} ;
	bool Consume(T& t) //取消息
	{
		typename TList::iterator iNext = iHead;
		++iNext;
		if (iNext != iTail)
		{
			/*iHead = iNext;
			t = *iHead;*/
			t = *iNext;
			iHead = iNext;
			return true;
		}

		return false;
	};
	bool Peek(T& t) //查看消息不删除
	{
		typename TList::iterator iNext = iHead;
		++iNext;
		if (iNext != iTail)
		{
			t = *iNext;
			return true;
		}

		return false;
	}
	bool IsEmpty()
	{
		typename TList::iterator iNext = iHead;
		++iNext;
		if (iNext != iTail)
		{
			return false;
		}
		else
		{
			return true;
		}
	};
	int GetMaxSize()
	{
		return list.max_size(); 
	};

	int GetSize()
	{
		return list.size();
	};

private:
	typedef std::list<T> TList;
	TList list;
    typename TList::iterator iHead, iTail;
};
#endif
 
.cpp
//队列使用
/****************声明队列***************/
CLockFreeQueue<CString> m_strQueue;
/**************队列插入元素***********/
m_strQueue.Produce("cs");
/*************声明线程****************/
AfxBeginThread(TestThread,0) ;
UINT TestThread(LPVOID param)
{
	while(1)
	{
		while(!m_strQueue.IsEmpty())
		{
			CString str;
			if ( m_strQueue.Consume(str) && !str.IsEmpty() )
			{
				//str就是你插入的元素了
			}
		}
		Sleep(1000);
	}
	return 0;
}


评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值