简体   繁体   中英

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.

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

Actually std::thread::id is printable using ostream (seethis ).

So you can do this:

#include <sstream>

std::ostringstream ss;

ss << std::this_thread::get_id();

std::string idstr = ss.str();

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

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM