Reputation: 461
The following code is for printing the process id of the 2 threads linux(ubuntu 14.04)
#include<pthread.h>
#include<stdio.h>
#include <unistd.h>
void* thread_function (void* arg)
{
fprintf (stderr, "child thread pid is %d\n", (int) getpid ());
/* Spin forever. */
while (1);
return NULL;
}
int main ()
{
pthread_t thread;
fprintf (stderr, "main thread pid is %d\n", (int) getpid ());
pthread_create (&thread, NULL, &thread_function, NULL);
/* Spin forever. */
while (1);
return 0;
}
And the output is
main thread pid is 3614
child thread pid is 3614
But shouldn't be the process id be different since GNU/Linux,threads are implemented as processes??
Upvotes: 3
Views: 2555
Reputation: 27542
Three separate concepts: the process id (getpid
), the pthreads thread id (pthread_self
) and the underlying linux thread id (gettid
).
There is no glibc wrapper for gettid
so it amounts to this
pid_t gettid(void)
{
return(syscall(SYS_gettid));
}
On the common pthreads programming level you shouldn't be concerned how the threads are implemented (though pdw explained it well enough). All this stuff is made deliberately opaque. There is no use for gettid
in any pthreads function. They all require the pthreads thread id.
There are two main reasons why people ask about linux thread ids. One, they want to understand the relationship of linux thread ids in relation to some system utility e.g. ps
, htop
. Two, there are literally a handful of linux specific system calls in which the linux tid is useful.
Upvotes: 3
Reputation: 8866
There's a terminology conflict here. It's true that each thread is a separate process as far as the Linux kernel is concerned. And therefore Linux assigns a new PID to each thread.
But that's not how POSIX works: according to POSIX all threads in a process should share the same PID. The Linux kernel calls this "Thread Group IDs" (TGID), and the getpid() function actually returns the TGID, in order to be POSIX-compliant.
Upvotes: 8