C++11 使用 std::atomic(多写入器,单使用者)的无锁队列

C++11 lockless queue using std::atomic (multi writer, single consumer)

本文关键字:使用者 队列 atomic std 使用 C++11      更新时间:2023-10-16

我使用 C++11 中的新std::atomic生成了无锁(无锁)队列的简单实现。我看不出我在这里做错了什么。

#include <atomic>
template<typename T>
class lockless_queue
{
public:
    template<typename DataType>
    struct node
    {
        node(const DataType& data)
          : data(data), next(nullptr) {}
        DataType data;
        node* next;
    };
    lockless_queue()
      : head_(nullptr) {}
    void produce(const T &data)
    {
        node<T>* new_node = new node<T>(data);
        // put the current value of head into new_node->next
        new_node->next = head_.load(std::memory_order_relaxed);
        // now make new_node the new head, but if the head
        // is no longer what's stored in new_node->next
        // (some other thread must have inserted a node just now)
        // then put that new head into new_node->next and try again
        while(!std::atomic_compare_exchange_weak_explicit(
            &head_,
            &new_node->next,
            new_node,
            std::memory_order_release,
            std::memory_order_relaxed)) {}
    }
    node<T>* consume_all()
    {
        // Reset queue and return head atomically
        return head_.exchange(nullptr, std::memory_order_consume);
    }
private:
    std::atomic<node<T>*> head_;
};
// main.cpp
#include <iostream>
int main()
{
    lockless_queue<int> s;
    s.produce(1);
    s.produce(2);
    s.produce(3);
    auto head = s.consume_all();
    while (head)
    {
        auto tmp = head->next;
        std::cout << tmp->data << std::endl;
        delete head;
        head = tmp;
    }
}

我的输出:

2
1
Segmentation fault (core dumped)

我可以有一些指示在哪里看或指示我可能做错了什么吗?

谢谢!

您正在取消引用tmp而不是head

while (head)
    {
        auto tmp = head->next;
        std::cout << tmp->data << std::endl;
        delete head;
        head = tmp;
    }

应该是:

while (head)
    {
        std::cout << head->data << std::endl;
        auto tmp = head->next;
        delete head;
        head = tmp;
    }

这就是为什么3不会出现在输出中,而Segmentation fault会显示的原因。

代码中还有另一个错误,在您开始尝试执行并发排队之前,该错误不会显示。 如果compare_exchange_weak_explicit失败,则意味着另一个线程设法更改了head指针,因此,在再次尝试 CAS 之前,您需要将head指针的新值重新加载到new_node->next中。 以下方法可以解决问题:

    while(!std::atomic_compare_exchange_weak_explicit(
        &head_,
        &new_node->next,
        new_node,
        std::memory_order_release,
        std::memory_order_relaxed)) {
        new_node->next = head_.load(std::memory_order_relaxed);
    }