Last active
September 28, 2018 08:12
-
-
Save drodil/a9c65f91c76c437badba45ea9eb06151 to your computer and use it in GitHub Desktop.
C++ human-readable thread id
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
#include <mutex> | |
#include <thread> | |
#include <unordered_map> | |
std::size_t get_thread_id() noexcept { | |
static std::size_t thread_idx = 0; | |
static std::mutex thread_mutex; | |
static std::unordered_map<std::thread::id, std::size_t> thread_ids; | |
std::lock_guard<std::mutex> lock(thread_mutex); | |
std::thread::id id = std::this_thread::get_id(); | |
auto iter = thread_ids.find(id); | |
if (iter == thread_ids.end()) { | |
iter = thread_ids.insert(std::pair<std::thread::id, std::size_t>(id, thread_idx++)).first; | |
} | |
return iter->second; | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment