在 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!)