街角_祝福

导航

C++一读一写无锁队列

// 一读一写的无锁管道队列
template<class T>
class PipelineList
{
private:
    template<class T>
    struct qnode
    {
        struct qnode *next;
        T data;
    };

    struct qnode<T>* volatile m_front;
    struct qnode<T>* volatile m_rear;

    bool init()
    {
        m_front = m_rear = new qnode<T>;
        if (!m_front)
        {
            return false;
        }
        m_front->next = 0;
        return true;
    }
    void destroy()
    {
        while (m_front)
        {
            m_rear = m_front->next;
            delete m_front;
            m_front = m_rear;
        }
    }

public:
    PipelineList()
    {
        init();
    }
    ~PipelineList()
    {
        destroy();
    }
    bool empty()
    {
        return (m_front == m_rear);
    }
    bool push(const T& e)
    {
        struct qnode<T> *p = new qnode<T>;
        if (!p)
        {
            return false;
        }
        p->next = 0;
        m_rear->next = p;
        m_rear->data = e;
        m_rear = p;
        return true;
    }
    bool pop(T& e)
    {
        if (m_front == m_rear)
        {
            return false;
        }
        struct qnode<T> *p = m_front;
        e = p->data;
        m_front = p->next;
        delete p;
        return true;
    }
};

posted on 2023-06-26 17:15  街角_祝福  阅读(56)  评论(0编辑  收藏  举报