当我们实现无锁数据结构时,为什么我们需要管理内存?

时间:2015-05-29 04:56:09

标签: c++11 concurrency lock-free

当我们实现无锁数据结构时,为什么我们需要管理内存?考虑以下堆栈示例,为什么"删除old_head"正如书中所说,pop函数中的语句会给其他线程带来问题吗?我没有看到"取消引用悬空指针的机会"可能会发生,我会多次运行代码,而不会出现任何错误。

template<typename T>
class lock_free_stack
{
private:
    struct node
    {
        std::shared_ptr<T> data;
        node* next;
        node(T const& data_) :
            data(std::make_shared<T>(data_))
        {}
    };
    std::atomic<node*> head;

public:
    void push(T const& data)
    {
        node* const new_node = new node(data);
        new_node->next = head.load();
        while (!head.compare_exchange_weak(new_node->next, new_node));
    }

    std::shared_ptr<T> pop()
    {
        node* old_head = head.load();
        while (old_head &&
            !head.compare_exchange_weak(old_head, old_head->next));
        auto res = old_head ? old_head->data : nullptr;
        delete old_head;
        return res;
    }
};

0 个答案:

没有答案
相关问题