15

I have a quick question about new thread created by pthread_create():

When I print the pid (get from getpid()) of main thread and the child thread, they are the same while when I using htop linux utility to show pid, they are different. Can any one explain this to me?? Thanks!!

kai@kai-T420s:~/LPI$ ./pthr_create
--------------------------------------
main thread: pid: 4845, ppid: 3335
child thread: pid: 4845, ppid: 3335

htop shows: Screenshot of the htop application showing a list of processes.

unwind
  • 391,730
  • 64
  • 469
  • 606
kai
  • 1,141
  • 3
  • 15
  • 25

2 Answers2

20

Linux implements pthreads() as Light-Weight-Processes, therefor they get a PID assigned.

Further information can be found at http://www.linuxforu.com/2011/08/light-weight-processes-dissecting-linux-threads/

there is also an example how to get the LWP-Pid for your thread.

#include <stdio.h>
#include <syscall.h>
#include <pthread.h>

int main()
{
     pthread_t tid = pthread_self();
     int sid = syscall(SYS_gettid);
     printf("LWP id is %d\n", sid);
     printf("POSIX thread id is %d\n", tid);
     return 0;
}
dwalter
  • 7,258
  • 1
  • 32
  • 34
2

Threads have both a process ID, returned from the getpid() syscall, and a thread ID, returned by gettid(). For the thread executing under main(), these will be identical. I don't know off hand which one htop is reporting, you should check the docs.

Andy Ross
  • 11,699
  • 1
  • 34
  • 31