本文給出一種C++無鎖隊列的實現代碼,主要用於一個線程讀取數據另外一個線程寫數據
代碼如下:
#ifndef LOCK_FREE_QUEUE_H_
#define LOCK_FREE_QUEUE_H_
//不加鎖隊列,適合一個線程讀取,一個線程寫
#include <list>
template <typename T>
class LockFreeQueue
{
public:
LockFreeQueue()
{
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;
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();
};
private:
typedef std::list<T> TList;
TList list;
typename TList::iterator iHead, iTail;
};
#endif