【问题标题】:Is boost shared_ptr<XX> thread-safe?boost shared_ptr<XX> 是线程安全的吗?
【发布时间】:2009-03-30 07:37:14
【问题描述】:

以下代码在使用 boost shared_ptr 时是否线程安全。 谢谢!

class CResource
{
xxxxxx
}
class CResourceBase
{
CResourceBase()
{
m_pMutex = new CMutex;
}
~CResourceBase()
{
ASSERT(m_pMutex != NULL);
delete m_pMutex;
m_pMutex = NULL;
}
private:
CMutex *m_pMutex;
public:
   void SetResource(shared_ptr<CResource> res)
   {
     CSingleLock lock(m_pMutex);
     lock.Lock();
     m_Res = res;
     lock.Unlock();
   }

   shared_ptr<CResource> GetResource()
   {
     CSingleLock lock(m_pMutex);
     lock.Lock();
     shared_ptr<CResource> res = m_Res;
     lock.Unlock();
     return 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);
    ...

【问题讨论】:

    标签: c++ boost thread-safety


    【解决方案1】:

    在你的例子中没有种族可能性(它正确锁定)。但是,您应该非常小心在多线程代码中使用 shared_ptr。请记住,您有可能通过来自不同线程的不同 shared_ptrs 访问相同的对象。例如,之后:

    Thread B:
        shared_ptr<CResource> nowResource;
        base.SetResource(nowResource);
        ...
    

    线程 B 仍然可以访问 nowResource。如果线程 A 获得资源 ptr,则两个线程可以同时使用对象无需任何同步!

    这当然是竞争条件。

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2012-03-05
      • 2023-03-29
      • 1970-01-01
      • 2012-07-14
      • 1970-01-01
      • 2013-09-24
      相关资源
      最近更新 更多