29

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.

user2859777
  • 293
  • 1
  • 3
  • 5

3 Answers3

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
19

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();
Nawaz
  • 353,942
  • 115
  • 666
  • 851
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
  • This is impressive, horrifying, and useful all at once. – Techrocket9 Nov 22 '22 at 23:40