c++ - 如何打印 pthread_t

标签 c++ c linux pthreads

已搜索,但没有找到令人满意的答案。

我知道没有可移植的方式来打印 pthread_t。

你是如何在你的应用中做到这一点的?

更新:

实际上我不需要 pthread_t,而是一些小的数字 id,在调试消息中标识不同的线程。

在我的系统(64 位 RHEL 5.3)上,它被定义为 unsigned long int,所以它是一个很大的数字,打印它会在调试行中占据一个有值(value)的位置。 gdb 如何分配短时间?

最佳答案

这将打印出 pthread_t 的十六进制表示。 ,不管那实际上是什么:

void fprintPt(FILE *f, pthread_t pt) {
  unsigned char *ptc = (unsigned char*)(void*)(&pt);
  fprintf(f, "0x");
  for (size_t i=0; i<sizeof(pt); i++) {
    fprintf(f, "%02x", (unsigned)(ptc[i]));
  }
}

为每个 pthread_t 打印一个小 id可以使用类似的东西(这次使用 iostreams):

void printPt(std::ostream &strm, pthread_t pt) {
  static int nextindex = 0;
  static std::map<pthread_t, int> ids;
  if (ids.find(pt) == ids.end()) {
    ids[pt] = nextindex++;
  }
  strm << ids[pt];
}

取决于平台和 pthread_t 的实际表示这里可能需要定义一个 operator<对于 pthread_t , 因为 std::map需要对元素进行排序:

bool operator<(const pthread_t &left, const pthread_t &right) {
  ...
}

关于c++ - 如何打印 pthread_t,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/1759794/

相关文章:

c - 如何为字符串动态分配内存空间并从用户那里获取该字符串?

c - 带分隔符的Strtok行为

c - 在 C 中,如何在尝试标记化之前测试剩余 strtok 字符串中的 NULL 值

linux - linux "gdb a.out param1 param2"是否将 param1 和 2 传递给 "gdb"或 "a.out"?

c++ - 使用 MPI_Scatter 时出现段错误

c++ - 操作数类型不兼容 "BSTR"和 "const char*"

c++ - ifstream eof 函数 (C++)

linux - 如何在 polyml 解释器中添加 readline 支持?

linux - 如何以 JSON、CSV 或其他格式获取 Ansible ad-hoc 命令的输出?

c++ - 如何逐行解析LLVM IR