ZBLOG

#include #include #include #include template class LockFreeQueue { public: LockFreeQueue() : head_(new Node), tail_(head_.load()) {} ~LockFreeQueue() { while (Nod...

这个队列中使用了Node结构体来表示队列中的节点,如果不想使用Node结构体,可以考虑使用std::atomicstd::shared_ptr<T>来代替。具体实现如下:

#include <atomic>
#include <condition_variable>
#include <iostream>
#include <memory>
#include <thread>

template <typename T>
class LockFreeQueue
{
public:
    LockFreeQueue() : head_(std::make_shared<Node>()), tail_(head_.load()) {}

    ~LockFreeQueue()
    {
        while (std::shared_ptr<Node> old_head = std::atomic_load_explicit(&head_, std::memory_order_relaxed))
        {
            head_ = std::atomic_load_explicit(&old_head->next_, std::memory_order_relaxed);
        }
    }

    void push(const T &value)
    {
        auto new_node = std::make_shared<Node>(value);
        auto tail = std::atomic_load_explicit(&tail_, std::memory_order_relaxed);
        std::atomic_store_explicit(&tail->next_, new_node, std::memory_order_release);
        std::atomic_store_explicit(&tail_, new_node, std::memory_order_release);
        size_.fetch_add(1, std::memory_order_release);
    }

    bool try_pop(T &value)
    {
        auto const old_head = std::atomic_load_explicit(&head_, std::memory_order_relaxed);
        auto const new_head = std::atomic_load_explicit(&old_head->next_, std::memory_order_relaxed);
        if (!new_head)
        {
            return false;
        }
        value = new_head->value_;
        std::atomic_store_explicit(&head_, new_head, std::memory_order_release);
        size_.fetch_sub(1, std::memory_order_release);
        return true;
    }

    bool empty() const
    {
        return std::atomic_load_explicit(&size_, std::memory_order_acquire) == 0;
    }

private:
    struct Node
    {
        T value_;
        std::shared_ptr<Node> next_;
        Node() : next_(nullptr) {}
        explicit Node(const T &value) : value_(value), next_(nullptr) {}
    };

    std::shared_ptr<Node> head_;
    std::shared_ptr<Node> tail_;
    std::atomic<size_t> size_{0};
    std::condition_variable cv_;
};

本站部分文章来源于网络,版权归原作者所有,如有侵权请联系站长删除。
转载请注明出处:https://golang.0voice.com/?id=1517

分享:
扫描分享到社交APP
上一篇
下一篇
发表列表
游客 游客
此处应有掌声~
评论列表

还没有评论,快来说点什么吧~

联系我们

在线咨询: 点击这里给我发消息

微信号:3007537140

上班时间: 10:30-22:30

关注我们
x

注册

已经有帐号?