gpt4 book ai didi

c++ - shared_ptr 是线程安全的开销是多少?

转载 作者:可可西里 更新时间:2023-11-01 18:25:26 25 4
gpt4 key购买 nike

std::shared_ptr 保证是线程安全的。我不知道典型的实现使用什么机制来确保这一点,但它肯定有一些开销。即使您的应用程序是单线程的,这种开销也会存在。

是上述情况吗?如果是这样,如果您没有使用线程安全保证,这是否意味着它违反了“您不为未使用的东西付费”的原则?

最佳答案

如果我们检查 cppreference std::shared_ptr 的页面他们在实现说明部分陈述了以下内容:

To satisfy thread safety requirements, the reference counters are typically incremented and decremented using std::atomic::fetch_add with std::memory_order_relaxed.

注意一个实际的实现很有趣,例如 libstdc++实现文件here说:

For the version of shared_ptr in libstdc++ the compiler and library are fixed, which makes things much simpler: we have an atomic CAS or we don't, see Lock Policy below for details.

选择锁定策略部分说(强调我的):

There is a single _Sp_counted_base class, which is a template parameterized on the enum __gnu_cxx::_Lock_policy. The entire family of classes is parameterized on the lock policy, right up to __shared_ptr, __weak_ptr and __enable_shared_from_this. The actual std::shared_ptr class inherits from __shared_ptr with the lock policy parameter selected automatically based on the thread model and platform that libstdc++ is configured for, so that the best available template specialization will be used. This design is necessary because it would not be conforming for shared_ptr to have an extra template parameter, even if it had a default value. The available policies are:

[...]

3._S_Single

This policy uses a non-reentrant add_ref_lock() with no locking. It is used when libstdc++ is built without --enable-threads.

并进一步说(强调我的):

For all three policies, reference count increments and decrements are done via the functions in ext/atomicity.h, which detect if the program is multi-threaded. If only one thread of execution exists in the program then less expensive non-atomic operations are used.

因此,至少在此实现中,您无需为未使用的内容付费。

关于c++ - shared_ptr 是线程安全的开销是多少?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/25780826/

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