为什么同一进程内主线程与新建线程调用getpid返回PID相同?
问题描述
我编写了如下基于pthread线程库的C语言测试程序,编译链接时需添加-pthread参数:
//compile and link with -pthread #include <stdio.h> #include <stdlib.h> #include <pthread.h> void *pthread_function( void *ptr ){ printf("Hello from the new thread, my pid is %d\n", getpid()); } int main() { printf("Hello from the calling process, my pid is %d\n", getpid()); pthread_t thread; int ret; ret = pthread_create( &thread, NULL, pthread_function, NULL); if (ret){ printf("ERROR; return code from pthread_create() is %d\n", ret); exit(-1); } /* Last thing that main() should do */ pthread_exit(NULL); }
运行该程序后得到如下执行结果:
Hello from the calling process, my pid is 4445
Hello from the new thread, my pid is 4445
核心疑问:为什么该场景下,调用进程(主线程)和新建线程通过getpid()获取到的PID值完全相同?
原因解释
这个现象是符合POSIX标准定义的正常行为,核心原因如下:
getpid()这个接口从设计之初,作用就是返回调用者所属的进程ID,不是返回线程的独立标识。PID是进程层面的归属标记,同一个进程创建出来的所有线程,本来就共享进程的虚拟内存、文件描述符、信号处理表、权限等全部核心资源,对外同属一个进程实体,共享同一个PID是完全符合语义的。- Linux平台的pthread基于NPTL(原生POSIX线程库)实现,内核调度线程时用轻量级进程(LWP)模型,每个线程在内核里有独立的调度实体,也有自己独有的内核线程ID(TID,可通过
gettid()系统调用获取),但这个内核层面的TID和用户态语义的PID不是同一个概念,不会被getpid()返回。
如果需要获取当前线程自身的唯一标识,应该调用pthread库提供的pthread_self()接口,而不是getpid()。你观察到的主线程和新线程输出相同PID不是运行错误,是系统设计时就定义好的标准行为。
内容的提问来源于stack exchange,提问作者Mariana Rodriguez
相关产品推荐
相关产品推荐

