Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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.

like image 763
user2859777 Avatar asked Oct 08 '13 18:10

user2859777


3 Answers

auto myid = this_thread::get_id();
stringstream ss;
ss << myid;
string mystring = ss.str();
like image 102
us2012 Avatar answered Oct 14 '22 03:10

us2012


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();
like image 33
Nawaz Avatar answered Oct 14 '22 03:10

Nawaz


"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];
}
like image 29
Walter Avatar answered Oct 14 '22 03:10

Walter