From 420b17ae65400f094f6db357b5921acfeaac547e Mon Sep 17 00:00:00 2001 From: gabime Date: Thu, 26 Jul 2018 21:09:40 +0300 Subject: [PATCH] Fix issue #769 --- include/spdlog/async.h | 18 +++++++++++++----- include/spdlog/details/registry.h | 26 +++++++++++--------------- 2 files changed, 24 insertions(+), 20 deletions(-) diff --git a/include/spdlog/async.h b/include/spdlog/async.h index c55440be..c2071834 100644 --- a/include/spdlog/async.h +++ b/include/spdlog/async.h @@ -22,6 +22,7 @@ #include "spdlog/details/thread_pool.h" #include +#include namespace spdlog { @@ -38,13 +39,20 @@ struct async_factory_impl template static std::shared_ptr create(const std::string &logger_name, SinkArgs &&... args) { - using details::registry; - auto sink = std::make_shared(std::forward(args)...); + auto ®istry_inst = details::registry::instance(); - // create default tp if not already exists. - auto tp = registry::instance().create_tp_once(details::default_async_q_size, 1); + //create global thread pool if not already exists.. + std::lock_guard(registry_inst.tp_mutex()); + auto tp = registry_inst.get_tp(); + if (tp == nullptr) + { + tp = std::make_shared(details::default_async_q_size, 1); + registry_inst.set_tp(tp); + } + + auto sink = std::make_shared(std::forward(args)...); auto new_logger = std::make_shared(logger_name, std::move(sink), std::move(tp), OverflowPolicy); - registry::instance().register_and_init(new_logger); + registry_inst.register_and_init(new_logger); return new_logger; } }; diff --git a/include/spdlog/details/registry.h b/include/spdlog/details/registry.h index 93f83ab1..982a39e3 100644 --- a/include/spdlog/details/registry.h +++ b/include/spdlog/details/registry.h @@ -68,24 +68,14 @@ public: void set_tp(std::shared_ptr tp) { - std::lock_guard lock(tp_mutex_); + std::lock_guard lock(tp_mutex_); tp_ = std::move(tp); } - // create tp only if not exists already - std::shared_ptr create_tp_once(size_t queue_size, size_t n_threads) - { - std::lock_guard lock(tp_mutex_); - if (tp_ == nullptr) - { - tp_ = std::make_shared(queue_size, n_threads); - } - return tp_; - } - + std::shared_ptr get_tp() { - std::lock_guard lock(tp_mutex_); + std::lock_guard lock(tp_mutex_); return tp_; } @@ -178,16 +168,22 @@ public: drop_all(); { - std::lock_guard lock(tp_mutex_); + std::lock_guard lock(tp_mutex_); tp_.reset(); } } + std::recursive_mutex &tp_mutex() + { + return tp_mutex_; + } + static registry &instance() { static registry s_instance; return s_instance; } + private: registry() @@ -210,7 +206,7 @@ private: } std::mutex logger_map_mutex_, flusher_mutex_; - std::mutex tp_mutex_; + std::recursive_mutex tp_mutex_; std::unordered_map> loggers_; std::unique_ptr formatter_; level::level_enum level_ = level::info;