gpt4 book ai didi

c++ - 原子 decref 实现之间的区别

转载 作者:塔克拉玛干 更新时间:2023-11-03 00:46:26 27 4
gpt4 key购买 nike

我一直在研究原子引用计数的实现。

库之间的大多数操作都非常一致,但我在“减少引用计数”操作中发现了惊人的多样性。 (请注意,通常情况下,shared 和 weak decref 之间的唯一区别是调用了哪个 on_zero()。异常(exception)情况在下面注明。)

如果除了“我们使用 seq_cst 因为我们不知道更好的东西”之外还有其他根据 C11/C++11 模型实现的实现(MSVC 做了什么?),请随意编辑它们中。

大多数示例最初是 C++,但在这里我将它们重写为 C,内联并规范化为 >= 1 约定:

#include <stdatomic.h>
#include <stddef.h>
typedef struct RefPtr RefPtr;
struct RefPtr {
_Atomic(size_t) refcount;
};
// calls the destructor and/or calls free
// on a shared_ptr, this also calls decref on the implicit weak_ptr
void on_zero(RefPtr *);

来自 Boost intrusive_ptr examplesopenssl :

void decref_boost_intrusive_docs(RefPtr *p) {
if (atomic_fetch_sub_explicit(&p->refcount, 1, memory_order_release) == 1) {
atomic_thread_fence(memory_order_acquire);
on_zero(p);
}
}

It would be possible to use memory_order_acq_rel for the fetch_sub operation, but this results in unneeded "acquire" operations when the reference counter does not yet reach zero and may impose a performance penalty.

但大多数其他人 ( Boost , libstdc++ , libc++ shared) 做其他事情:

void decref_common(RefPtr *p) {
if (atomic_fetch_sub_explicit(&p->refcount, 1, memory_order_acq_rel) == 1)
on_zero(p);
}

但是 libc++ 可以 something different for the weak count .奇怪的是,这是在一个外部源文件中:

void decref_libcxx_weak(RefPtr *p) {
if (atomic_load_explicit(&p->refcount, memory_order_acquire) == 1)
on_zero(p);
else
decref_common(p);
}

那么问题是:实际差异是什么?

子问题:评论有错吗?特定平台做什么(在 aarch64 上,ldar 会比 dmb ishld 便宜吗?还有 ia64?)?在什么情况下可以使用较弱的版本(例如,如果 dtor 是 nop,如果删除器只是 free,...)?

另见 Atomic Reference CountingWhy is an acquire barrier needed before deleting the data in an atomically reference counted smart pointer?

最佳答案

源代码中记录了 libc++ 的选择:

NOTE: The acquire load here is an optimization of the very common case where a shared pointer is being destructed while having no other contended references.

libc++ 编码人员观察到,大多数时候,当最后一个 shared_ptr 被销毁时,没有 weak_ptr 引用共享对象。据我所知,至少在 x86 上,读取-修改-写入指令比读取指令更广泛。因此,对于最常见的情况,他们决定避免执行扩展且无用的读取-修改-写入操作。标准库的其他实现不执行此优化。

关于c++ - 原子 decref 实现之间的区别,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/55988701/

27 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com