如何在c ++中将std :: thread :: id转换为字符串?

use*_*777 11 c++ multithreading stdthread

如何std::thread::id在C++中对字符串进行类型转换?我试图将生成的输出强制转换 std::this_thread::get_id()为字符串或char数组.

us2*_*012 21

auto myid = this_thread.get_id();
stringstream ss;
ss << myid;
string mystring = ss.str();
Run Code Online (Sandbox Code Playgroud)


Wal*_*ter 6

“转换”std::thread::id为 astd::string只是为您提供一些独特但无用的文本。或者,您可以将其“转换”为一个便于人类识别的小整数:

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];
}
Run Code Online (Sandbox Code Playgroud)


Naw*_*waz 5

实际上std::thread::id是可以使用打印的ostream(请参阅参考资料)。

因此,您可以执行以下操作:

#include <sstream>

std::ostringstream ss;

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

std::string idstr = ss.str();
Run Code Online (Sandbox Code Playgroud)