How to print pthread_t
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) { ...}
In this case, it depends on the operating system, since the POSIX standard no longer requires pthread_t
to be an arithmetic type:
IEEE Std 1003.1-2001/Cor 2-2004, item XBD/TC2/D6/26 is applied, adding
pthread_t
to the list of types that are not required to be arithmetic types, thus allowingpthread_t
to be defined as a structure.
You will need to look in your sys/types.h
header and see how pthread_t
is implemented; then you can print it how you see fit. Since there isn't a portable way to do this and you don't say what operating system you are using, there's not a whole lot more to say.
Edit: to answer your new question, GDB assigns its own thread ids each time a new thread starts:
For debugging purposes, gdb associates its own thread number—always a single integer—with each thread in your program.
If you are looking at printing a unique number inside of each thread, your cleanest option would probably be to tell each thread what number to use when you start it.