是 boost shared_ptr <XXX>线程安全?

我有一个关于 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会不会是最新的?nowResourcenowResource 被释放时会导致程序崩溃还是会破坏 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_ptr objects offer the same level of thread safety as built-in types. A shared_ptr instance can be "read" (accessed using only const operations) simultaneously by multiple threads. Different shared_ptr instances can be "written to" (accessed using mutable operations such as operator= 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.

相关文章