问题
In this file, the boost::lockfree::detail::freelist
class is used to manage storage for a lock-free data structure (e.g., a queue), using a free list.
The deallocate_impl
method is used to free nodes by linking them back into the free list (a freed node becomes the new head of the free list, displacing the old head). This method is supposed to be thread-safe and lock-free. The original source code of one instance is duplicated here with my comments annotated to point out the suspicious code (potential bug?):
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;
}
}
I have seen the same implementation in Boost 1.62.0 too
回答1:
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()
writes previous value of pool_
into old_pool
after each call. Documentation for compare_exchange_weak().
However, if "index" is the same as old_pool.get_index()...
This probably cannot happen, since node with that index was not moved to free list yet.
来源:https://stackoverflow.com/questions/42909951/if-this-is-not-a-bug-in-boostlockfreedetailfreelist-what-am-i-missing-her