From 58a30fe347e2778514b48b0f2de3c4f2bcfec82d Mon Sep 17 00:00:00 2001 From: lisyarus Date: Wed, 30 Sep 2020 16:16:08 +0300 Subject: [PATCH] Fix thread registration --- libs/log/source/log.cpp | 31 ++++++++++++++++++++++--------- 1 file changed, 22 insertions(+), 9 deletions(-) diff --git a/libs/log/source/log.cpp b/libs/log/source/log.cpp index a3f7cc14..bae04605 100644 --- a/libs/log/source/log.cpp +++ b/libs/log/source/log.cpp @@ -19,6 +19,7 @@ namespace psemek::log max_thread_name_length = length; } + static std::mutex thread_names_mutex; static std::unordered_map thread_names; void register_thread(std::string name) @@ -28,14 +29,18 @@ namespace psemek::log void register_thread(std::thread::id id, std::string name) { - auto it = thread_names.find(id); - if (it != thread_names.end()) - throw std::runtime_error("Thread \"" + name + "\" already registered!"); + { + std::lock_guard lock{thread_names_mutex}; - if (name.size() > max_thread_name_length) - throw std::runtime_error("Thread \"" + name + "\" name is too long"); + auto it = thread_names.find(id); + if (it != thread_names.end()) + throw std::runtime_error("Thread \"" + name + "\" already registered!"); - thread_names[id] = name; + if (name.size() > max_thread_name_length) + throw std::runtime_error("Thread \"" + name + "\" name is too long"); + + thread_names[id] = name; + } put_message(level::info, "Thread \"" + name + "\" registered"); } @@ -59,14 +64,22 @@ namespace psemek::log auto const millis = std::chrono::duration_cast(clock::now().time_since_epoch()).count() % 1000; auto const id = std::this_thread::get_id(); - auto const it = thread_names.find(id); - auto const & thread_name = (it == thread_names.end()) ? unknown_thread_name : it->second; + + std::string const * thread_name; + { + std::lock_guard lock{thread_names_mutex}; + auto const it = thread_names.find(id); + if (it == thread_names.end()) + thread_name = &unknown_thread_name; + else + thread_name = &(it->second); + } std::ostringstream os; os << '[' << std::put_time(&tm, "%Y %b %d %H:%M:%S.") << std::setw(3) << std::setfill('0') << millis << ']' - << '[' << std::setw(max_thread_name_length) << std::setfill(' ') << thread_name << ']' + << '[' << std::setw(max_thread_name_length) << std::setfill(' ') << *thread_name << ']' << '[' << std::setw(7) << l << ']' << ' ' << message;