How to extract thread ID from pthread_self () to integer variable? That is something like this:

int a=pthread_self(); 

Or if this cannot be done, then how to display the thread ID with cout. In the style of C it turns out:

 printf("thread id = %d\n", pthread_self()); 

and the string

 cout<<pthread_self(); 

gives an error

  • what mistake? Describe in more detail. Also try static_cast <int> (pthread_self ()) - jNX
  • syscall(SYS_gettid) - VTT
  • typedef unsigned long int pthread_t; so cast into this type before output. - NewView 1:14 pm
  • "In C style, it works ..." No, it doesn't. It has long been no guarantee that pthread_t is of arithmetic type. Trying to print it this way is useless. - AnT 1:14 pm

2 answers 2

The stream ID type is free and can be executed in any version by different compilers. You can draw as a list of bytes like this:

 // g++ -Wall -Wpedantic showthrid.cpp # include <iostream> typedef union { volatile pthread_t tid; volatile uint8_t bid [sizeof(pthread_t)]; } uid ; int main(){ uid u ; u.tid = pthread_self(); std::cout<<"pthread_self = "<<std::hex; for(int i=sizeof(pthread_t);i;){ -- i ; std::cout<<((unsigned int )u.bid[i])<<"."; } std::cout<<std::endl; std::cout<<" = "<<((size_t)u.tid)<<std::endl; } $ ./a.out pthread_self = 0.0.7f.3b.21.d0.4d.80. = 7f3b21d04d80 

And if you find a numeric type with the right size, then throw that value onto that type. I have a size of 8 bytes. That is, you can cram into size_t .

  • Reading an inactive bid field is an undefined behavior. - VTT
  • @VTT volatile usually saves from smart compilers. So this code will plow 99%. - AlexGlebe

pthread_self returns a stream handle that is not particularly printable or readable. You can get a numeric stream id like this:

 #ifndef _GNU_SOURCE #define _GNU_SOURCE #endif #include <unistd.h> #include <sys/syscall.h> #include <errno.h> #include <stdlib.h> #include <stdio.h> int main() { long id; errno = 0; id = syscall(SYS_gettid); if(0 != errno) { perror("syscall(SYS_gettid) failed"); abort(); } fprintf(stdout, "thread id %li", id); return 0; }