shared_ptr是线程安全的开销? [英] What's the overhead from shared_ptr being thread-safe?

查看:494
本文介绍了shared_ptr是线程安全的开销?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

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

std::shared_ptr is guaranteed to be thread-safe. I don't know what mechanism the typical implementations use to ensure this, but surely it must have some overhead. And that overhead would be present even in the case that your application is single-threaded.

是上述情况吗?如果是这样,这意味着它违反了你不支付你不使用的原则,如果你不使用线程安全保证?

Is the above the case? And if so, does that means it violates the principle of "you don't pay for what you don't use", if you aren't using the thread-safety guarantees?

推荐答案

如果我们查看 cppreference 页面 std :: shared_ptr ,他们在实施说明中说明了以下内容: em> section:

If we check out cppreference page for std::shared_ptr they state the following in the Implementation notes section:


为了满足线程安全性要求,引用计数器通常使用 std :: atomic :: fetch_add std :: memory_order_relaxed

有趣的是注意一个实际的实现,例如 libstdc ++ 实施文档这里说:

It is interesting to note an actual implementation, for example the libstdc++ implementation document here says:


对于libstdc ++中的shared_ptr版本,库
是固定的,这使得事情更简单:我们有一个原子CAS或
我们没有,详情请参阅下面的锁策略。

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.

选择锁定政策部分(强调我):


有一个_Sp_counted_base类,它是一个模板
,在enum __gnu_cxx :: _ Lock_policy上参数化。整个系列
的类在锁策略上被参数化,直到
__shared_ptr,__weak_ptr和__enable_shared_from_this。实际的std :: shared_ptr类继承自__shared_ptr,锁定策略
参数根据libstdc ++配置的线程模型和
平台自动选择,以便最佳可用
将使用模板专业化
。这个设计是必要的,因为
它不符合shared_ptr有一个额外的模板
参数,即使它有一个默认值。可用的政策有:

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

3._S_Single

此策略使用不可重入的add_ref_lock(),没有锁定。当libstdc ++构建时没有--enable-threads时使用。

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

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


对于所有三个策略,引用计数增量和减量是
通过ext / atomicity.h中的函数完成,它检测程序
是否是多线程的。 如果
程序中只有一个执行线程,那么使用更便宜的非原子操作

所以至少在这个实现中,你不支付你不使用的东西。

So at least in this implementation you don't pay for what you don't use.

这篇关于shared_ptr是线程安全的开销?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆