正如我们所知,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不会使任何进程或者线程退出。它仅仅是使函数返回到调用者那里,即返回调用的地方。