gpt4 book ai didi

c++ - 如何避免 recursive_mutex

转载 作者:行者123 更新时间:2023-11-28 02:37:50 25 4
gpt4 key购买 nike

我有一个 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/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com