正如我們所知,exit()是退出進程(無論它放在任何地方都會導致整個進程的退出)。而線程退出就是pthread_exit()。
前面說如果主線程不等待線程執行完畢而退出,子線程就會沒有打印。
如果我們把主控線程當做一個線程去退出的話,會發生什么事情呢?
*********************************************************************************************
#include <stdio.h>
#include <stdlib.h>
#include <unistd.h>
#include <string.h>
#include <sys/types.h>
#include <fcntl.h>
#include <sys/stat.h>
#include <sys/mman.h>
#include <pthread.h>
void *thread_func(void *arg)
{
int cn = (int)arg;
sleep(cn);
printf("In thread %d.\n",cn+1);
printf("Will out thread.\n");
return NULL;
}
int main(int argc,char *argv[])
{
int ret;
int i;
pthread_t tid;
for(i=0;i<5;i++)
{
ret = pthread_create(&tid,NULL,&thread_func,(void*)i);
if(ret)
{
printf("Thread create failed.\n");
exit(1);
}
}
printf("In main id=%lu,pid = %lu\n",pthread_self(),getpid());
pthread_exit(NULL);
}
*********************************************************************************************
執行結果:
以上看已明顯的看出,main線程打印后就結束啦,而子線程依舊可以打印出來。這是因為主線程調用pthread_exit()之后只是主線程退出,而進程還在運行。
還有return關鍵字,return不會使任何進程或者線程退出。它僅僅是使函數返回到調用者那里,即返回調用的地方。