0

我有一个我正在尝试解决的 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/

谢谢,

4

1 回答 1

2

正在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();
}

现在您既不需要关心锁定也不需要关心迭代器的有效性。

于 2014-11-14T22:05:46.640 回答