在同一进程中处理线程的id

laz*_*der 2 c linux pthreads

以下代码用于打印2线程linux的进程id(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;
}
Run Code Online (Sandbox Code Playgroud)

输出是

main thread pid is 3614
child thread pid is 3614
Run Code Online (Sandbox Code Playgroud)

但是不应该是因为GNU/Linux的进程id不同,线程是作为进程实现的?

pdw*_*pdw 7

这里有一个术语冲突.就Linux内核而言,每个线程都是一个独立的进程.因此Linux为每个线程分配一个新的PID.

但这不是POSIX的工作方式:根据POSIX,进程中的所有线程都应共享相同的PID.Linux内核调用此"线程组ID"(TGID),并且getpid()函数实际返回TGID,以便符合POSIX标准.