diff --git a/libs/async/source/threadpool.cpp b/libs/async/source/threadpool.cpp index dacbd410..6eab0d30 100644 --- a/libs/async/source/threadpool.cpp +++ b/libs/async/source/threadpool.cpp @@ -21,9 +21,9 @@ namespace psemek::async for (std::size_t th = 0; th < thread_count; ++th) { std::string tname = thread_count == 1 ? name : util::to_string(name, '#', th); - threads_.emplace_back([this, tname = std::move(tname)] + threads_.emplace_back([this, tname = std::move(tname)]() mutable { - log::register_thread(tname); + log::thread_registrator reg(std::move(tname)); for (bool running = true; running;) { auto task = task_queue_.pop(); diff --git a/libs/log/include/psemek/log/log.hpp b/libs/log/include/psemek/log/log.hpp index 1382481a..81d9d1b7 100644 --- a/libs/log/include/psemek/log/log.hpp +++ b/libs/log/include/psemek/log/log.hpp @@ -13,6 +13,28 @@ namespace psemek::log void register_thread(std::string name); void register_thread(std::thread::id id, std::string name); + void unregister_thread(std::thread::id id); + + struct [[maybe_unused]] thread_registrator + { + thread_registrator(std::string name, std::thread::id id) + : id_{id} + { + register_thread(id_, std::move(name)); + } + + thread_registrator(std::string name) + : thread_registrator(std::move(name), std::this_thread::get_id()) + {} + + ~thread_registrator() + { + unregister_thread(id_); + } + + private: + std::thread::id id_; + }; void put_message(level l, std::string const & message); diff --git a/libs/log/source/log.cpp b/libs/log/source/log.cpp index e1f6a699..34f8f7f9 100644 --- a/libs/log/source/log.cpp +++ b/libs/log/source/log.cpp @@ -45,6 +45,27 @@ namespace psemek::log put_message(level::info, "Thread \"" + name + "\" registered"); } + void unregister_thread(std::thread::id id) + { + std::string name; + { + std::lock_guard lock{thread_names_mutex}; + + auto it = thread_names.find(id); + if (it == thread_names.end()) + { + std::ostringstream os; + os << "Thread " << id << " not found!"; + throw std::runtime_error(os.str()); + } + + name = it->second; + thread_names.erase(it); + } + + put_message(level::info, "Thread \"" + name + "\" unregistered"); + } + static ::tm safe_localtime(std::time_t const & time) { static std::mutex mutex;