如何打印的pthread_t [英] How to print pthread_t

查看:1349
本文介绍了如何打印的pthread_t的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

搜索,但跨越一个令人满意的答案不来。

Searched, but don't come across a satisfying answer.

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

I know there's no a portable way to print a pthread_t.

你如何在你的应用程序呢?

How do you do it in your app?

更新:

其实我不需要的pthread_t,但一些小的数字ID,识别调试消息不同的线程。

Actually I don't need pthread_t, but some small numeric id, identifying in debug message different threads.

在我的系统(64位RHEL 5.3),它定义为unsigned long int类型,所以这是很大的数字,只是打印出来吃在调试线的宝贵的地方。如何 GDB分配短TIDS?

On my system (64 bit RHEL 5.3) it's defined as unsigned long int, so it's big number and just printing it eats a valuable place in debug line. How does gdb assign short tids?

推荐答案

这将打印出的的pthread_t ,不管是什么,实际上是十六进制再presentation是:

This will print out a hexadecimal representation of a pthread_t, no matter what that actually is:

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]));
  }
}

要(使用的iostream这次)只是打印小ID为每个的pthread_t 这样的事情可以使用:

To just print a small id for a each pthread_t something like this could be used (this time using 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 的实际再presentation可能在这里需要定义一个运营商的LT上; 的pthread_t ,因为的std ::地图需要的元素的顺序:

Depending on the platform and the actual representation of pthread_t it might here be necessary to define an operator< for pthread_t, because std::map needs an ordering on the elements:

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

这篇关于如何打印的pthread_t的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆