From 03f0ca965ea804216bdc681f9093d1df2a0f76ed Mon Sep 17 00:00:00 2001 From: orignal Date: Mon, 15 Aug 2016 22:36:58 -0400 Subject: [PATCH] fixed race condition --- NetDbRequests.cpp | 25 ++++++++++++++++--------- NetDbRequests.h | 2 +- 2 files changed, 17 insertions(+), 10 deletions(-) diff --git a/NetDbRequests.cpp b/NetDbRequests.cpp index c3966597..474d3693 100644 --- a/NetDbRequests.cpp +++ b/NetDbRequests.cpp @@ -68,8 +68,7 @@ namespace data dest->SetRequestComplete (requestComplete); { std::unique_lock l(m_RequestedDestinationsMutex); - if (!m_RequestedDestinations.insert (std::make_pair (destination, - std::shared_ptr (dest))).second) // not inserted + if (!m_RequestedDestinations.insert (std::make_pair (destination, dest)).second) // not inserted return nullptr; } return dest; @@ -77,20 +76,28 @@ namespace data void NetDbRequests::RequestComplete (const IdentHash& ident, std::shared_ptr r) { - auto it = m_RequestedDestinations.find (ident); - if (it != m_RequestedDestinations.end ()) - { + std::shared_ptr request; + { + std::unique_lock l(m_RequestedDestinationsMutex); + auto it = m_RequestedDestinations.find (ident); + if (it != m_RequestedDestinations.end ()) + { + request = it->second; + m_RequestedDestinations.erase (it); + } + } + if (request) + { if (r) - it->second->Success (r); + request->Success (r); else - it->second->Fail (); - std::unique_lock l(m_RequestedDestinationsMutex); - m_RequestedDestinations.erase (it); + request->Fail (); } } std::shared_ptr NetDbRequests::FindRequest (const IdentHash& ident) const { + std::unique_lock l(m_RequestedDestinationsMutex); auto it = m_RequestedDestinations.find (ident); if (it != m_RequestedDestinations.end ()) return it->second; diff --git a/NetDbRequests.h b/NetDbRequests.h index 0bab7080..debf1273 100644 --- a/NetDbRequests.h +++ b/NetDbRequests.h @@ -59,7 +59,7 @@ namespace data private: - std::mutex m_RequestedDestinationsMutex; + mutable std::mutex m_RequestedDestinationsMutex; std::map > m_RequestedDestinations; }; }