您的位置:首页 > 编程语言 > C语言/C++

C++无锁队列实现 (2012-05-15 07:46:26)

2014-07-04 18:01 330 查看

转载▼

标签:


c无锁队列


线程安全队列


it

分类: 常用源码
本文给出一种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
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: