我有一个我正在尝试解决的 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;
}
}
}
OnConnectionDisconnected 在多个线程 (n) 上调用,并且 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/
谢谢,