为什么在引用计数器上需要内存顺序限制

Why there need memory order limit on reference counter?

本文关键字:内存 顺序 引用 计数器 为什么      更新时间:2023-10-16

boost::atomic为例,unref函数:

void intrusive_ptr_release(const X * x)
{
  if (x->refcount_.fetch_sub(1, boost::memory_order_release) == 1) {
    boost::atomic_thread_fence(boost::memory_order_acquire);
    delete x;
  }
}

1: fetch_sub操作受到memory_order_release的限制,这可以防止前面的操作在超过该点后被重新排序。但是在什么情况下会出现这种现象呢?

2:除了原子op上的memory_order_release,为什么在删除前还有一个memory_order_acquire ?

对于第一个问题,它防止(*x)的任何使用在fetch_sub之后重新排序(当引用计数可能为0并且因此禁止使用时)。可能原因是CPU重排序或编译器重排序。第二个问题只是释放的镜像;释放保护存储,获取保护负载。

看起来refcount_fetch_sub(1, memory_order_acq_rel)也可以工作,但它只保护了refcount。