Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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?

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?

like image 907
dimba Avatar asked Nov 18 '09 23:11

dimba


People also ask

What data type is pthread_t?

A thread ID is represented by the pthread_t data type. Implementations are allowed to use a structure to represent the pthread_t data type, so portable implementations can't treat them as integers. Therefore, a function must be used to compare two thread IDs.

What is a pthread_t?

pthread_t is the data type used to uniquely identify a thread. It is returned by pthread_create() and used by the application in function calls that require a thread identifier.

What is pthread_t in Linux?

pthread_t could be any number of bytes. It could be a char, an int, a pointer, or a struct... But you neither need to know nor to care. If you need the size for allocation purposes, you use sizeof(pthread_t) . The only type of variable you can assign it to is another pthread_t .

How do I get thread ID?

The pthread_self() function is used to get the ID of the current thread. This function can uniquely identify the existing threads. But if there are multiple threads, and one thread is completed, then that id can be reused. So for all running threads, the ids are unique.


1 Answers

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) {   ... } 
like image 100
sth Avatar answered Sep 20 '22 20:09

sth