在 linux 世界中,主线程退出了,子线程是否退出是要看主线程的退出方式。
主线程以 return 的方式退出。
主线程以 pthread_exit() 函数的方式退出。
前者,main() 执行完 return 之后,实际上会调用 exit() 函数,该函数除了执行关闭IO等操作之外,还会执行关掉其他子线程的操作。
后者,在主线程中执行 pthread_exit() ,实际上是提前结束了 main 的主线程,也就无法执行后续的 exit() 函数了。所以,这种方法是可以达到主线程退出子线程继续运行的目的。
栗子:
#include <iostream>#include <pthread.h>#include <unistd.h>void *func(void *args){while (true){std::cout << "I am func." << std::endl;sleep(3);}}int main(){pthread_t pid = 0;pthread_create(&pid, nullptr, func, nullptr);pthread_detach(pid);pthread_exit(nullptr);return 0;}
对于后来来说,由于子线程没有办法继续运行,所以子线程所在的进程也就变成了僵尸进程。验证方法:
ps -ef | grep test
结果:
xcl 1672 3102 0 17:40 pts/0 00:00:00 [test.o] <defunct>
“defunct”标识就是僵尸进程标识。
(SAW:Game Over!)