[英]How to avoid recursive_mutex
我正在嘗試解決一例recursive_mutex。 這是一段解釋問題的代碼。
void OnConnectionDisconnected()
{
boost::lock_guard<boost::mutex> lock ( m_mutexConnectionSet );
IPCSyncConnectionSharedPtrSet::iterator it = m_IPCSyncConnectionSet.find(spConnection);
if ( it != m_IPCSyncConnectionSet.end())
{
m_IPCSyncConnectionSet.erase(*it);
}
}
void ShutdownServer()
{
boost::lock_guard<boost::mutex> lock ( m_mutexConnectionSet );
IPCSyncConnectionSharedPtrSet::iterator it = m_IPCSyncConnectionSet.begin();
for (; it != m_IPCSyncConnectionSet.end(); )
{
if (*it)
{
IPCSyncConnectionSharedPtr spIPCConnection = (*it);
it++;
//This call indirectly calls OnConnectionDisconnected and erase the connection.
spIPCConnection->Disconnect();
}
else
{
++it;
}
}
}
當連接處於活動狀態或斷開連接時,在任何時候都可以在多個線程(n)上調用OnConnectionDisconnected,並且ShutdownServer只能在一個線程上調用。 ShutdownServer遍歷所有連接,並在每個連接上調用Disconnect,這間接調用了OnConnectionDisconnected,而我實際上是在擦除連接。 由於在其他線程中修改了連接集,因此在訪問m_IPCSyncConnectionSet之前,我已經鎖定了互斥鎖。
我需要在上面的示例代碼中使用recursive_mutex,因為在調用Shutdown時,互斥鎖在同一線程上被鎖定兩次。
任何人都可以建議我如何解決上述問題並避免recursive_lock嗎? recurive_mutex會根據這篇文章殺死您http://www.fieryrobot.com/blog/2008/10/14/recursive-locks-will-kill-you/
謝謝,
在ShutdownServer()
中使用容器的臨時副本。 除了鎖定問題之外,迭代由另一個函數修改的容器也不是一個好主意(即使此特定的容器類型在擦除元素時不會使所有迭代器無效,這樣的代碼也將非常脆弱且不必要地復雜)。
void ShutdownServer()
{
boost::lock_guard<boost::mutex> lock ( m_mutexConnectionSet );
auto connections = m_IPCSyncConnectionSet;
lock.unlock();
for (auto it = connections.begin(); it != connections.end(); ++it)
if (*it)
(*it)->Disconnect();
}
現在,您既不必關心鎖定,也不必關心迭代器的有效性。
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.