Is boost shared_ptr lt;XXXgt; thread safe?(是 boost shared_ptr lt;XXXgt;线程安全?)
问题描述
我有一个关于 boost::shared_ptr 的问题.
I have a question about boost::shared_ptr<T>.
有很多线程.
using namespace boost;
class CResource
{
  // xxxxxx
}
class CResourceBase
{
public:
   void SetResource(shared_ptr<CResource> res)
   {
     m_Res = res;
   }
   shared_ptr<CResource> GetResource()
   {
      return m_Res;
   }
private:
   shared_ptr<CResource> m_Res;
}
CResourceBase base;
//----------------------------------------------
// Thread_A:
    while (true)
    {
       //...
       shared_ptr<CResource> nowResource = base.GetResource();
       nowResource.doSomeThing();
       //...
    }
// Thread_B:
    shared_ptr<CResource> nowResource;
    base.SetResource(nowResource);
    //...
第一季度
如果Thread_A不关心nowResource是最新的,这部分代码会不会有问题?
Q1
If Thread_A do not care the nowResource is the newest, will this part of code have problem?
我的意思是当Thread_B没有完全SetResource()时,Thread_A通过GetResource()得到一个错误的智能点代码>?
I mean when Thread_B do not SetResource() completely, Thread_A get a wrong smart point by GetResource()?
线程安全是什么意思?
如果不关心资源是不是最新的,shared_ptr 在 nowResource 被释放时会导致程序崩溃还是会破坏 shared_ptr?
If I do not care about whether the resource is newest, will the shared_ptr<CResource> nowResource crash the program when the nowResource is released or will the problem destroy the shared_ptr<CResource>?
推荐答案
来自 boost 文档:
shared_ptr 对象提供相同的内置线程安全级别类型.shared_ptr 实例可以是读取"(仅使用 const 访问操作)同时由多个线程.不同 shared_ptr实例可以写入"(使用可变操作访问例如 operator= 或 reset)同时由多个线程(即使这些实例是副本,并共享相同的引用计数在下面.)
shared_ptrobjects offer the same level of thread safety as built-in types. Ashared_ptrinstance can be "read" (accessed using only const operations) simultaneously by multiple threads. Differentshared_ptrinstances can be "written to" (accessed using mutable operations such asoperator=or reset) simultaneously by multiple threads (even when these instances are copies, and share the same reference count underneath.)
任何其他同时访问都会导致未定义的行为.
Any other simultaneous accesses result in undefined behavior.
所以你的使用是不安全的,因为它使用了m_res的同时读写.boost 文档中的示例 3 也说明了这一点.
So your usage is not safe, since it uses simultaneous read and write of m_res. Example 3 in the boost documentation also illustrates this.
您应该使用单独的 mutex 保护对 SetResource/GetResource 中的 m_res 的访问.
You should use a separate mutex that guards the access to m_res in SetResource/GetResource.
这篇关于是 boost shared_ptr <XXX>线程安全?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持编程学习网!
本文标题为:是 boost shared_ptr <XXX>线程安全?
				
        
 
            
        基础教程推荐
- 静态库、静态链接动态库和动态链接动态库的 .lib 文件里面是什么? 2021-01-01
 - 常量变量在标题中不起作用 2021-01-01
 - 如何通过C程序打开命令提示符Cmd 2022-12-09
 - 我有静态或动态 boost 库吗? 2021-01-01
 - 这个宏可以转换成函数吗? 2022-01-01
 - 在 C++ 中计算滚动/移动平均值 2021-01-01
 - 如何将 std::pair 的排序 std::list 转换为 std::map 2022-01-01
 - C++结构和函数声明。为什么它不能编译? 2022-11-07
 - 如何在 C++ 中初始化静态常量成员? 2022-01-01
 - 如何检查GTK+3.0中的小部件类型? 2022-11-30
 
    	
    	
    	
    	
    	
    	
    	
    	
						
						
						
						
						
				
				
				
				