簡體   English   中英

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

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

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

您的示例中沒有比賽的可能(已正確鎖定)。 但是,在多線程代碼中使用shared_ptr應該非常小心。 請記住,您有可能通過不同線程的不同shared_ptrs訪問同一對象。 例如,之后:

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

線程B仍然可以訪問nowResource。 如果線程A獲得資源ptr,則兩個線程可以同時使用對象, 而無需任何同步!

這當然是比賽條件。

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM