ZBLOG

#include #include #include template class LockFreeQueue { public: LockFreeQueue() : head_(new Node), tail_(head_.load()) {} void push(const T &item) { std::unique_ptr new_node(new Nod...

#include #include #include

template class LockFreeQueue { public:

LockFreeQueue() : head_(new Node), tail_(head_.load()) {}

void push(const T &item) {
    std::unique_ptr<Node> new_node(new Node);
    new_node->data = item;
    while (true) {
        Node *tail = tail_.load();
        Node *next = tail->next.load();
        if (tail == tail_.load()) {
            if (next == nullptr) {
                if (tail->next.compare_exchange_weak(next, new_node.get())) {
                    tail_.compare_exchange_weak(tail, new_node.get());
                    new_node.release();
                    return;
                }
            } else {
                tail_.compare_exchange_weak(tail, next);
            }
        }
    }
}

bool try_pop(T &item) {
    while (true) {
        Node *head = head_.load();
        Node *tail = tail_.load();
        Node *next = head->next.load();
        if (head == head_.load()) {
            if (head == tail) {
                if (next == nullptr) {
                    return false;
                }
                tail_.compare_exchange_weak(tail, next);
            } else {
                item = next->data;
                if (head_.compare_exchange_weak(head, next)) {
                    // delete head; 不需要手动释放内存,unique_ptr 会自动释放
                    return true;
                }
            }
        }
    }
}

private:

struct Node {
    T data;
    std::atomic<Node *> next{nullptr};
    Node() {}
    Node(const Node&) = delete;
    Node& operator=(const Node&) = delete;
};

std::atomic<Node *> head_;
std::atomic<Node *> tail_;

};

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

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

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

联系我们

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

微信号:3007537140

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

关注我们
x

注册

已经有帐号?