How to print pthread
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?
Update:
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?
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) {
...
}
GDB uses the thread-id (aka kernel pid, aka LWP) for short numbers on Linux. Try:
#include <syscall.h>
...
printf("tid = %dn", syscall(SYS_gettid));
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 allowing pthread_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.
链接地址: http://www.djcxy.com/p/58330.html上一篇: 例如,JNI +类型转换(例如,签名为无符号短符号)
下一篇: 如何打印pthread