views:

249

answers:

1

Is the following code thread safe when using boost shared_ptr. Thanks!

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);
    ...
+3  A: 

There is no race possibility in you example (it' correctly locked). However, you should be very careful with shared_ptr in multithread code. Please, keep in mind that there is possibility that you have access do the same object through different shared_ptrs from different threads. For example, after:

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

thread B still has access to the nowResource. If thread A gets the resource ptr, both thread can use object at the same time without any synchronization!

This would be of course race condition.

oo_olo_oo