From 6d56df787e971cf369598236a59a223033fab6ca Mon Sep 17 00:00:00 2001 From: eidheim Date: Tue, 9 Aug 2016 21:48:08 +0200 Subject: [PATCH] Simplified Git::get_repository --- src/git.cc | 33 ++++++++++++--------------------- src/git.h | 3 --- 2 files changed, 12 insertions(+), 24 deletions(-) diff --git a/src/git.cc b/src/git.cc index 9e4599b..018e82e 100644 --- a/src/git.cc +++ b/src/git.cc @@ -3,8 +3,6 @@ bool Git::initialized=false; std::mutex Git::mutex; -std::unordered_map, size_t> > Git::repositories; -std::mutex Git::repositories_mutex; std::string Git::Error::message() noexcept { const git_error *last_error = giterr_last(); @@ -262,25 +260,18 @@ void Git::initialize() noexcept { std::shared_ptr Git::get_repository(const boost::filesystem::path &path) { initialize(); - std::lock_guard lock(repositories_mutex); - auto root_path=std::make_shared(Repository::get_root_path(path).generic_string()); - auto it=repositories.find(*root_path); - Repository *repository_ptr; - if(it!=repositories.end()) { - it->second.second++; - repository_ptr=it->second.first.get(); - } - else { - it=repositories.emplace(*root_path, std::make_pair(std::unique_ptr(new Repository(*root_path)), 1)).first; - repository_ptr=it->second.first.get(); - } - return std::shared_ptr(repository_ptr, [root_path](Repository *) { - std::lock_guard lock(repositories_mutex); - auto it=repositories.find(*root_path); - it->second.second--; - if(it->second.second==0) - repositories.erase(it); - }); + static std::unordered_map > cache; + static std::mutex mutex; + + std::lock_guard lock(mutex); + auto root_path=Repository::get_root_path(path).generic_string(); + auto it=cache.find(root_path); + if(it==cache.end()) + it=cache.emplace(root_path, std::weak_ptr()).first; + auto instance=it->second.lock(); + if(!instance) + it->second=instance=std::shared_ptr(new Repository(root_path)); + return instance; } boost::filesystem::path Git::path(const char *cpath, size_t cpath_length) noexcept { diff --git a/src/git.h b/src/git.h index a0c763b..9d41ac5 100644 --- a/src/git.h +++ b/src/git.h @@ -88,9 +88,6 @@ private: ///Mutex for thread safe operations static std::mutex mutex; - static std::unordered_map, size_t> > repositories; - static std::mutex repositories_mutex; - ///Call initialize in public static methods static void initialize() noexcept;