提高:: shared_ptr的是它的安全使用它在多线程? [英] boost::shared_ptr is it safe to use it in multiple threads?

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

问题描述

我试图找到了一段时间的答案,但我失败了。

I was trying to find the answer for some time but I failed.

让我们假设我们有一个的shared_ptr 从一个线程创建的。然后我们通过这个的shared_ptr 另一个2个线程(使用一些队​​列为例)。所以从这个时刻有原始的shared_ptr 2份,指向同一个原始指针。
两个老板线程会拿自己这个的shared_ptr 的副本从队列中。然后,他们将它传递到另一个线程还是会摧毁它。

Lets assume that we have a shared_ptr created from one thread. Then we pass this shared_ptr to another 2 threads (using some queue for example). So from this moment there are 2 copies of the original shared_ptr, pointing to the same raw pointer. Both owner threads will take their copies of this shared_ptr from the queue. Then they will pass it to another thread or will destroy it.

问题是 - 它的安全?将正确地破坏了原始指针(不会有种族引用计数器?)

Question is - is it safe? Will the raw pointer destroyed correctly (there will be no race to reference counter?)

推荐答案

借助提升文档状态:

不同的shared_ptr实例可以写入simultaneosly多个线程​​(即使这些实例是拷贝,而且共享下层的引用计数(使用可变操作,如操作员访问=或复位)。

Different shared_ptr instances can be "written to" (accessed using mutable operations such as operator= or reset) simultaneosly by multiple threads (even when these instances are copies, and share the same reference count underneath.)

(重点煤矿)

因此​​,这里的关键是你是否复制的的的boost :: shared_ptr的取值线程与否之间。如果您创建副本(安全的方式来使用的shared_ptr )你没有关于线程安全任何后顾之忧。然而,如果你通过了的shared_ptr 通过引用或指针,因此实际使用的相同的的shared_ptr 在不同的线程,你也不必担心线程安全,如文档描述。

So the crux here is whether you copy the boost::shared_ptrs between threads or not. If you create copies (the "safe" way to use shared_ptrs) you don't have any worries about thread-safety. If however you pass the shared_ptr by reference or pointer, and hence are using the actual same shared_ptr in different threads, you would have to worry about thread-safety, as described in the docs.

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

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