c++ - 如何避免 recursive_mutex

标签 c++ multithreading boost synchronization 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;
            }
        }
    }

OnConnectionDisconnected 在多个线程 (n) 上调用,以及 ShutdownServer 在连接处于事件状态或断开连接时在任何时候仅在一个线程上调用。 ShutdownServer 遍历所有连接并在每个连接上调用 Disconnect 间接调用 OnConnectionDisconnected 我实际上删除连接的地方。我在访问 m_IPCSyncConnectionSet 之前锁定了互斥锁,因为连接集在其他线程中被修改了。

我需要在上面的示例代码中使用 recursive_mutex,因为在调用 Shutdown 时,mutex 在同一个线程上被锁定了两次。

谁能建议我如何解决上述问题并避免 recursive_lock ?根据本文 http://www.fieryrobot.com/blog/2008/10/14/recursive-locks-will-kill-you/,recurive_mutex 会杀了你

谢谢,

最佳答案

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

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

关于c++ - 如何避免 recursive_mutex,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/26929150/

相关文章:

python - 使用Thread和Process的不同结果

sockets - boost::asio 套接字 async_* 链

c++ - 运行 boost::asio 套接字示例时我传递给客户端的参数是什么

c++ - 是否有可能获得指向 std::vector<unsigned int> 数据的原始指针?

c++ - 在 Qt Creator 中加载具有相对路径的文件

c++ - 使用 C++ 重置 curl header

c++ - C++ 中的字符指针

android - 中断 HttpURLConnection 请求 Android

c++ - 线程指针的 vector ,push_back导致崩溃

c++ - 使用 boost::future/boost::promise 无法跨线程正确传播异常