Add thread unregistering in log

This commit is contained in:
Nikita Lisitsa 2021-03-04 14:29:39 +03:00
parent 2f56f0caa2
commit 9cba2d1c16
3 changed files with 45 additions and 2 deletions

View file

@ -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();

View file

@ -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);

View file

@ -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;