ZBLOG

#include #include #include "terra_memory_pool.h" template class LockFreeQueue { public: LockFreeQueue() : head_(new Node), tail_(head_.load()), memory_pool_(sizeof(Node) * 100) {} ~LockFreeQueue() { ...

这个队列的代码在大多数情况下是正确的,但是可能存在一些问题:

  1. 内存泄漏 在析构函数中,只有头指针被删除了,而其他节点却没有被释放,导致内存泄漏。应该遍历整个链表并释放所有节点的内存。

  2. 内存碎片 每次push操作都会分配一个新的节点,这可能导致频繁的内存分配和释放,从而产生内存碎片。应该使用内存池来重复利用节点的内存。

  3. 无法支持移动语义和自定义分配器 这个队列只支持复制语义,无法支持移动语义。而且,它使用默认的new和delete来分配和释放节点的内存,不支持自定义分配器。

以下是经过优化的代码:

#include #include #include “terra_memory_pool.h”

template > class LockFreeQueue { public:

using allocator_type = typename Alloc::template rebind<Node>::other;

LockFreeQueue() : head_(new Node), tail_(head_.load()), size_(0) {}
~LockFreeQueue()
{
    while (Node *const old_head = head_)
    {
        Node *next_node = old_head->next_;
        allocator_.destroy(old_head);
        allocator_.deallocate(old_head, 1);
        head_ = next_node;
    }
}

void push(const T &value)
{
    Node *new_node = allocator_.allocate(1);
    allocator_.construct(new_node, Node(value));
    Node *tail = tail_.load(std::memory_order_relaxed);
    tail->next_ = new_node;
    tail_.store(new_node, std::memory_order_release);
    size_.fetch_add(1, std::memory_order_release);
}

bool try_pop(T &value)
{
    Node *const old_head = head_.load(std::memory_order_relaxed);
    Node *const new_head = old_head->next_;
    if (new_head == nullptr)
    {
        return false;
    }
    value = std::move(new_head->value_);
    head_.store(new_head, std::memory_order_release);
    size_.fetch_sub(1, std::memory_order_release);
    allocator_.destroy(old_head);
    allocator_.deallocate(old_head, 1);
    return true;
}

bool empty() const
{
    return size_.load(std::memory_order_acquire) == 0;
}

private:

struct Node
{
    T value_;
    Node *next_;
    explicit Node(const T &value) : value_(value), next_(nullptr) {}
};

std::atomic<Node *> head_;
std::atomic<Node *> tail_;
std::atomic<size_t> size_;
allocator_type allocator_;

};

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

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

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

联系我们

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

微信号:3007537140

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

关注我们
x

注册

已经有帐号?