无锁对象池

14 阅读1分钟

下面是一个基于无锁设计的对象池的简单实现示例:

#include <atomic>
#include <vector>
#include <memory>

template<typename T>
class LockFreeObjectPool {
private:
    struct Node {
        std::shared_ptr<T> data;
        std::atomic<Node*> next;
        Node(const T& value) : data(std::make_shared<T>(value)), next(nullptr) {}
    };

    std::atomic<Node*> head;
    std::vector<Node*> nodes;

public:
    LockFreeObjectPool() : head(nullptr) {}

    ~LockFreeObjectPool() {
        for (Node* node : nodes) {
            delete node;
        }
    }

    void add(const T& value) {
        Node* newNode = new Node(value);
        newNode->next.store(head.load());
        while (!head.compare_exchange_weak(newNode->next, newNode));
        nodes.push_back(newNode);
    }

    std::shared_ptr<T> acquire() {
        Node* oldHead = head.load();
        while (oldHead != nullptr && !head.compare_exchange_weak(oldHead, oldHead->next.load()));
        if (oldHead == nullptr) {
            return nullptr;
        }
        return oldHead->data;
    }
};

这个无锁对象池的实现与前面的示例类似,不同之处在于它存储了 std::shared_ptr<T> 而不是直接存储对象本身。这样做的好处是可以避免在对象池中使用对象时,对象被销毁的情况。对象被放回对象池时,其引用计数会减少,但只有在没有任何引用时对象才会被销毁。