How to typecast std::thread::id to string in C++? I am trying to typecast output generated by std::this_thread::get_id() to a string or char array.
3 Answers
Actually std::thread::id is printable using ostream (see this).
So you can do this:
#include <sstream>
std::ostringstream ss;
ss << std::this_thread::get_id();
std::string idstr = ss.str();
Comments
You may "convert" it to a small integer number useful for easy identification by humans:
std::size_t index(const std::thread::id id)
{
static std::size_t nextindex = 0;
static std::mutex my_mutex;
static std::unordered_map<std::thread::id, std::size_t> ids;
std::lock_guard<std::mutex> lock(my_mutex);
auto iter = ids.find(id);
if(iter == ids.end())
return ids[id] = nextindex++;
return iter->second
}
4 Comments
lmat - Reinstate Monica
Not a strict answer to the question, but a very useful answer nonetheless!
Valera Dubrava
What the purpose of these code? Index does not show "real" thread sequence number. It almost the same "useless text" but useless number.
Walter
It provides a unique id to the thread. Your "real thread sequence number" is less unique, since it is implementation dependent -- while most implementations use pthreads, that's not guaranteed, nor is the existence of a "real thread sequence number".
Techrocket9
This is impressive, horrifying, and useful all at once.
std::thread::id?