How to print pthread_t


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

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

How do you do it in your app?


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

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?

7/9/2013 9:36:25 AM

Accepted Answer

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

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

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) {
4/13/2012 12:43:53 AM

GDB uses the thread-id (aka kernel pid, aka LWP) for short numbers on Linux. Try:

  #include <syscall.h>

    printf("tid = %d\n", syscall(SYS_gettid));

Licensed under: CC-BY-SA with attribution
Not affiliated with: Stack Overflow