如果将普通列表用作spsc队列会发生什么事情?

我知道将普通列表用作spsc队列不是线程安全的。可是我不知道为什么如果这样做会发生什么问题? 我阅读了有关mpsc-queue的论文,并对代码做了一些更改。我将其更改为spsc-queue。但是我不知道我的spsc_queue是否是thread_safe。

template <typename T>
class SPSCQueue
{
    struct Node
    {
        T *item = nullptr;
        Node *next = nullptr;
        bool is_sentinel;

        Node() : is_sentinel(true) {}
    };
public:
    SPSCQueue() 
    {
        m_head = new Node;
        m_tail = m_head;
    }

    ~SPSCQueue()
    {
        Node *tmp = m_head;
        while (m_head != nullptr)
        {
            temp = m_head;
            m_head = m_head->next;
            delete temp;
        }
    }

    void Enqueue(T *item)
    {
        if (item == nullptr) return;
        Node *last_tail = m_tail;
        m_tail = new Node();
        last_tail->item = item;
        last_tail->next = m_tail;
        last_tail->is_sentinel = false;
    }

    T *Dequeue()
    {
        if(m_head->is_sentinel) return nullptr;

        Node *last_head = m_head;
        T *item = last_head->item;
        m_head = last_head->next;
        delete last_head;
        return item;
    }

private:
    Node *m_head = nullptr;
    Node *m_tail = nullptr;
};
zjd1987zjd 回答:如果将普通列表用作spsc队列会发生什么事情?

暂时没有好的解决方案,如果你有好的解决方案,请发邮件至:iooj@foxmail.com
本文链接:https://www.f2er.com/3159714.html

大家都在问