diff --git a/include/connection_cache.hpp b/include/connection_cache.hpp index a999232..5ed4e2d 100644 --- a/include/connection_cache.hpp +++ b/include/connection_cache.hpp @@ -6,6 +6,7 @@ #include #include #include +#include namespace TrRouting { @@ -46,6 +47,7 @@ class ScenarioConnectionCacheOne : public ScenarioConnectionCache { virtual void set(boost::uuids::uuid uuid, std::shared_ptr cache); private: + mutable std::shared_mutex mutex; //Reader/Writer locking std::optional lastUuid; std::shared_ptr lastConnection; }; @@ -68,6 +70,7 @@ class ScenarioConnectionCacheAll : public ScenarioConnectionCache { virtual void set(boost::uuids::uuid uuid, std::shared_ptr cache); private: + mutable std::shared_mutex mutex; //Reader/Writer locking std::map > connectionSets; }; diff --git a/src/connection_cache.cpp b/src/connection_cache.cpp index a06ab06..87c9959 100644 --- a/src/connection_cache.cpp +++ b/src/connection_cache.cpp @@ -8,6 +8,7 @@ namespace TrRouting { // ScenarioConnectionCacheOne std::optional> ScenarioConnectionCacheOne::get(boost::uuids::uuid uuid) const { + std::shared_lock lock(mutex); //Sharing lock when reading if (uuid == lastUuid) { return std::optional(lastConnection); } else { @@ -16,12 +17,14 @@ namespace TrRouting { } void ScenarioConnectionCacheOne::set(boost::uuids::uuid uuid, std::shared_ptr cache) { + std::unique_lock lock(mutex); //Exclusive lock when writing lastUuid = uuid; lastConnection = cache; } // ScenarioConnectionCacheAll std::optional> ScenarioConnectionCacheAll::get(boost::uuids::uuid uuid) const { + std::shared_lock lock(mutex); //Sharing lock when reading // Lookup the scenario uuid in the map. If found, returns it, if not, return a null_opt auto connectionSetItr = connectionSets.find(uuid); if (connectionSetItr != connectionSets.end()) { @@ -33,7 +36,7 @@ namespace TrRouting { void ScenarioConnectionCacheAll::set(boost::uuids::uuid uuid, std::shared_ptr cache) { spdlog::debug("Caching connection set for scenario {}", boost::uuids::to_string(uuid)); - + std::unique_lock lock(mutex); //Exclusive lock when writing connectionSets[uuid] = cache; } }