ZBLOG

给代码

以下是一个简单的C++无锁队列的实现示例,不使用C++11特性:

#include <atomic>

template<typename T>
class LockFreeQueue {
private:
    struct Node {
        T data;
        Node* next;
        
        Node(const T& value) : data(value), next(nullptr) {}
    };
    
    std::atomic<Node*> head;
    std::atomic<Node*> tail;
    
public:
    LockFreeQueue() : head(nullptr), tail(nullptr) {}
    
    void enqueue(const T& value) {
        Node* newNode = new Node(value);
        
        while (true) {
            Node* last = tail.load();
            Node* next = last->next;

            if (last == tail.load()) { // Ensure no other thread has modified 'tail'
                if (next == nullptr) { // 'last' is actually the last node
                    if (std::atomic_compare_exchange_strong(&last->next, &next, newNode)) {
                        std::atomic_compare_exchange_strong(&tail, &last, newNode);
                        return;
                    }
                } else { // 'tail' was not pointing to the last node
                    std::atomic_compare_exchange_strong(&tail, &last, next);
                }
            }
        }
    }

    bool dequeue(T& result) {
        while (true) {
            Node* first = head.load();
            Node* last = tail.load();
            Node* next = first->next;

            if (first == head.load()) { // Ensure no other thread has modified 'head'
                if (first == last) { // Queue is empty or being modified by another thread
                    if (next == nullptr)
                        return false; // Queue is empty
                    
                    std::atomic_compare_exchange_strong(&tail, &last, next);
                } else { // Read 'data' before CAS
                    result = next->data;
                    
                    if (std::atomic_compare_exchange_strong(&head, &first, next)) {
                        delete first; // Safe to delete the old head node now
                        return true;
                    }
                }
            }
        }
    }
};

注意,此示例只提供了一个基本的无锁队列实现,并没有处理内存管理和线程同步的所有细节。实际使用时,请确保正确处理内存释放、ABA问题以及线程安全等方面的细节,并进行适当的测试和验证。


内容由零声教学AI助手提供,问题来源于学员提问

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

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

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

联系我们

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

微信号:3007537140

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

关注我们
x

注册

已经有帐号?