'How to convert std::thread::id to string in c++?

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.



Solution 1:[1]

auto myid = this_thread::get_id();
stringstream ss;
ss << myid;
string mystring = ss.str();

Solution 2:[2]

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

Solution 3:[3]

"converting" std::thread::id to a std::string just gives you some unique but otherwise useless text. Alternatively, 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::map<std::thread::id, std::size_t> ids;
  std::lock_guard<std::mutex> lock(my_mutex);
  if(ids.find(id) == ids.end())
    ids[id] = nextindex++;
  return ids[id];
}

Sources

This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.

Source: Stack Overflow

Solution Source
Solution 1 NutCracker
Solution 2 Nawaz
Solution 3 user2672165