解析C++无锁队列的实现代码

时间:2021-11-29 04:17:05

本文给出一种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