对于程序来说,如果主进程在子进程还未结束时就已经退出,那么Linux内核会将子进程的父进程ID改为1(也就是init进程),当子进程结束后会由init进程来回收该子进程。
那如果是把进程换成线程的话,会怎么样呢?假设主线程在子线程结束前就已经退出,子线程会发生什么?
在一些论坛上看到许多人说子线程也会跟着退出,其实这是错误的,原因在于他们混淆了线程退出和进程退出概念。实际的答案是主线程退出后子线程的状态依赖于它所在的进程,如果进程没有退出的话子线程依然正常运转。如果进程退出了,那么它所有的线程都会退出,所以子线程也就退出了。
#include <pthread.h> #include <unistd.h> #include <stdio.h> void * func (void * arg) { pthread_t main_tid = *static_cast <pthread_t *>(arg); pthread_cancel(main_tid); while (true ) { } return NULL ; } int main (int argc, char * argv[]) { pthread_t main_tid = pthread_self(); pthread_t tid = 0 ; pthread_create(&tid, NULL , func, &main_tid); while (true ) { printf ("main loops\n" ); } sleep(1 ); printf ("main exit\n" ); return 0 ; }
void * func (void * arg) { while (true ) { printf ("child loops\n" ); } return NULL ; } int main (int argc, char * argv[]) { pthread_t main_tid = pthread_self(); pthread_t tid = 0 ; pthread_create(&tid, NULL , func, &main_tid); sleep(1 ); printf ("main exit\n" ); return 0 ; }
pthread_self
的man page中有这样一段话:
Thread IDs are guaranteed to be unique only within a process. A thread ID may be reused after a terminated thread has been joined, or a detached thread has terminated.
所以在内核中唯一标识线程ID的线程号只能通过系统调用syscall(SYS_gettid)获取。
W.Richard Stevens.
UNIX环境高级编程(第3版), 人民邮电出版社, 2014
Linux man page.
pthread_self(3)