简体   繁体   English

是助推shared_ptr <XX> 线程安全的?

[英]Is boost shared_ptr<XX> thread-safe?

Is the following code thread safe when using boost shared_ptr. 使用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);
    ...

There is no race possibility in you example (it' correctly locked). 您的示例中没有比赛的可能(已正确锁定)。 However, you should be very careful with shared_ptr in multithread code. 但是,在多线程代码中使用shared_ptr应该非常小心。 Please, keep in mind that there is possibility that you have access do the same object through different shared_ptrs from different threads. 请记住,您有可能通过不同线程的不同shared_ptrs访问同一对象。 For example, after: 例如,之后:

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

thread B still has access to the nowResource. 线程B仍然可以访问nowResource。 If thread A gets the resource ptr, both thread can use object at the same time without any synchronization! 如果线程A获得资源ptr,则两个线程可以同时使用对象, 而无需任何同步!

This would be of course race condition. 这当然是比赛条件。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM