Recently, I've read in the "Advanced Linux Programming" book (http://www.advancedlinuxprogramming.com/alp-folder/alp-ch04-threads.pdf, Chapter 4.5) that on GNU/Linux POSIX threads are implemented as processes and that there is some kind of "manager thread" which does some control work.
When I run the following example from this book:
#include <stdio.h>
#include <pthread.h>
void* thread_func(void *arg)
{
fprintf(stderr, "thread: %d\n", (int)getpid());
while(1);
return NULL;
}
int main()
{
fprintf(stderr, "main: %d\n", (int)getpid());
pthread_t thread;
pthread_create(&thread, NULL, thread_func, NULL);
while(1);
return 0;
}
I've received the same PID for the main thread and child thread, while the book says that it can be different & that there is another PID, which corresponds to the so-called "manager thread." I've tried to find some information about this "manager thread", but it's proving difficult.
UPD. I have no doubts about behaivour of my program, but there is some confusion about behaivour, explained on the book - in particular, under which circumstances it can be true?
i've received the same PID both for main thread and child thread
That is normal and expected behavior. These threads you created co-exist in the same process, so getpid()
returns ID for that process. If you want to distinguish threads, use pthread_self()
(POSIX-compatible, but not system-wide unique) or gettid()
(Linux specific).
Internally, all processes and threads in Linux are managed by universal object called task (and defined by task_struct
), and each task has it's own ID. However, first task is a handle process thus called task group leader. And getpid()
returns PID of that task group leader.
So in your case, thread_func()
thread prints PID of its leader, main()
task, and main()
thread print PID of itself.
I suggest you to dive into kernel internals. It provides cleaner view of such things - try for example Robert Love book "Linux Kernel Development". Some information on threads/processes/etc. may be found here: http://www.win.tue.nl/~aeb/linux/lk/lk-10.html
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With