2

使用 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);
    ...
4

1 回答 1

4

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

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

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

这当然是比赛条件。

于 2009-03-30T08:32:07.810 回答