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.
Asked
Active
Viewed 3.3k times
29

user2859777
- 293
- 1
- 3
- 5
-
what do you mean by "convert"? what do you want to do with the "converted" `std::thread::id`? – Walter Oct 08 '13 at 18:11
-
@Walter I want to log it for debug purpose – Zoli May 16 '23 at 10:47
3 Answers
46
auto myid = this_thread::get_id();
stringstream ss;
ss << myid;
string mystring = ss.str();

NutCracker
- 11,485
- 4
- 44
- 68

us2012
- 16,083
- 3
- 46
- 62
7
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
}

Michael Ribbons
- 1,753
- 1
- 16
- 26

Walter
- 44,150
- 20
- 113
- 196
-
Not a strict answer to the question, but a very useful answer nonetheless! – lmat - Reinstate Monica Sep 24 '21 at 20:27
-
What the purpose of these code? Index does not show "real" thread sequence number. It almost the same "useless text" but useless number. – Valera Dubrava May 30 '22 at 08:14
-
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". – Walter May 31 '22 at 17:23
-