c++ - 如果这不是 boost::lockfree::detail::freelist 中的错误,我在这里缺少什么?

标签 c++ multithreading boost queue lock-free

this fileboost::lockfree::detail::freelist 类用于管理无锁数据结构(例如队列)的存储,使用 free list . deallocate_impl 方法用于通过将节点链接回空闲列表来释放节点(已释放的节点成为空闲列表的新头部,取代旧头部)。此方法应该是线程安全且无锁的。此处复制了一个实例的原始源代码,并注释了我的注释以指出可疑代码(潜在错误?):

void deallocate_impl (index_t index)
{
    freelist_node * new_pool_node =
           reinterpret_cast<freelist_node*>(NodeStorage::nodes() + index);

    // Shouldn't this line be placed inside the loop?
    // The loop continues as long as the compare-and-exchange fails,
    // which happens if the pool head has been concurrently updated.
    // In that case, we MUST reload the new value of "pool_" to
    // reuse its tag, link the new free-list head to it and
    // compare against in the compare_and_exchange call.
    tagged_index old_pool = pool_.load(memory_order_consume);

    for(;;) {
        // The old pool head tag is reused here without causing
        // any ABA problems. However, if "index" is the same as
        // old_pool.get_index(), a self-reference is written.
        tagged_index new_pool (index, old_pool.get_tag());
        new_pool_node->next.set_index(old_pool.get_index());

        if (pool_.compare_exchange_weak(old_pool, new_pool))
            return;
    }
}

我在 Boost 1.62.0 中也看到了相同的实现

最佳答案

The loop continues as long as the compare-and-exchange fails, which happens if the pool head has been concurrently updated. In that case, we MUST reload the new value of "pool_" to reuse its tag...

compare_exchange_weak() 在每次调用后将 pool_ 的先前值写入 old_poolDocumentation for compare_exchange_weak() .

However, if "index" is the same as old_pool.get_index()...

这可能不会发生,因为具有该索引的节点尚未移至空闲列表。

关于c++ - 如果这不是 boost::lockfree::detail::freelist 中的错误,我在这里缺少什么?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/42909951/

相关文章:

c++ - initializer_list 和模板类型推导

c++ - 程序在 Debug 中运行良好,但在 Release 中运行不正常

java - IntentService自己的Thread

c++ - 如何在头文件库中定义(非方法)函数

c++ - 如何查找 boost 图中是否存在顶点?

Unix 上的 C++ : Differences in threading libraries?

c++ - 使用内联命名空间进行 API 版本控制

c++ - 什么是n = n ^ 1U << i?

c++ - 将 std::lock_guard 与 try_lock 一起使用

c++ - 在 std::thread 中 joinable() 然后 join() 线程安全吗?