先说结论再做论证:
All of the threads in a process are peers: any thread can join with any other thread in the process. --- POSIX文档(man pthread_join NOTES)
也就是说,在linux中所有线程都是并列的关系,一个线程的结束&退出不会影响到其他线程的执行。即使是被称为“主线程”的线程退出了也是如此。
有人说:“主线程从main函数退出之后,会结束掉所有线程啊”。没错,不过在这种情况下所有线程都结束不是因为主线程结束退出导致的,而是因为main函数在结尾处return了。“main函数的return操作等价于调用了 exit 函数”----。exit都调用了,那么整个进程肯定是要结束的。
为了更好的说明这个问题,请看下面这个小程序:
在linux中,所有线程都是并列的关系,一个线程的退出结束不会影响到其他线程。即使是被称为“主线程”的线程退出也是如此。
void * threadcb(void * arg)
{
for(int i = 0; i < 5; i++)
{
sleep(1);
cout << "thread A count: " << i << endl;
}
cout << "thread A quit: " << endl;
}
int main()
{
pthread_t tid;
pthread_create(&tid,0,threadcb,0);
pthread_detach(tid);
cout << "main thread call pthread_exit"<< endl;
pthread_exit(0);
cout << "main thread dead : "<< endl;
return 0;
}
如图,主线程这次没有在main函数中直接return,而是调用了pthread_exit()结束自己。线程A继续执行自己的任务,直到结束。
证明了线程组中所有的线程包括主线程都是并列关系,任何一个线程的死亡,都不会影响到其他线程。