Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to get pid from pthread

in RH Linux, every pthread is mapping to a pid, which can be monitored in tools such as htop. but how can i get the pid of a thread? getpid() just return the pid of the main thread.

like image 918
Shawn Avatar asked Sep 01 '11 13:09

Shawn


2 Answers

There are two thread values that get confused. pthread_self() will return the POSIX thread id; gettid() will return the OS thread id. The latter is linux specific and not guaranteed to be portable but probably what you are really looking for.

EDIT As PlasmaHH notes, gettid() is called via syscall(). From the syscall() man page:

   #define _GNU_SOURCE
   #include <unistd.h>
   #include <sys/syscall.h>
   #include <sys/types.h>

   int
   main(int argc, char *argv[])
   {
       pid_t tid;

       tid = syscall(SYS_gettid);
   }
like image 171
Duck Avatar answered Sep 20 '22 17:09

Duck


pthread_self();

Can be called to return the ID of the calling thread.

Also PID is process Id, A thread has thread Id not PID. All threads running in the same process will have the same PID.

like image 44
Alok Save Avatar answered Sep 19 '22 17:09

Alok Save