How to convert std :: thread :: id to string in C ++?

How to attribute std::thread::id to a string in C ++? I am trying to get the type inference generated by std::this_thread::get_id() into a string or char array.

+7
c ++ multithreading stdthread
source share
3 answers
 auto myid = this_thread.get_id(); stringstream ss; ss << myid; string mystring = ss.str(); 
+15
source share

In fact, std::thread::id can be printed 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(); 
+4
source share

The "conversion" of std::thread::id to std::string just gives you unique but otherwise useless text. In addition, you can "convert" it into a small integer, useful for easily identifying people:

 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, st::size_t> ids; std::lock_guard<std::mutex> lock(my_mutex); if(ids.find(id) == ids.end()) ids[id] = nextindex++; return ids[id]; } 
+4
source share

All Articles