问题:为什么调用sleep函数
答:可能新创建的线程还没运行到打印的方法主线程就结束了,而主线程结束,所有线程都会结束了。
2线程挂起
有时候我们在一个线程中创建了另外一个线程,主线程要等到创建的线程返回了,获取该线程的返回值后主线程才退出。这个时候就需要用到线程挂起。
int pthread_join(pthread_t th, void **thr_return);。
pthread_join函数用于挂起当前线程,直至th指定的线程终止为止。
#include<pthread.h>
#include<stdio.h>
#include<stdlib.h>
#include<string.h>
#include<errno.h>
void * func(void * arg)
{
int i=0;
for(;i<5;i++)
{
printf("func run%dn",i);
sleep(1);
}
int * p = (int *)malloc(sizeof(int));
*p=11;
return p;
}
int main()
{
pthread_t t1,t2;
int err = pthread_create(&t1,NULL,func,NULL);
if(err!=0)
{
printf("thread_create Failed:%sn",strerror(errno));
}else{
printf("thread_create successn");
}
void *p=NULL;
pthread_join(t1,&p);
printf("线程退出:code=%dn",*(int*)p);
return EXIT_SUCCESS;
}
函数执行结果

我们主函数一直在等待创建的线程执行完,并且得到了线程执行结束的返回值
3线程终止
进程终止时exit()函数,那么线程终止是什么呢?
线程终止的三种情况:
线程只是从启动函数中返回,返回值是线程的退出码。
线程可以被同一进程中的其他线程取消。
线程调用pthread_exit。
#include<pthread.h>
#include<stdio.h>
#include<stdlib.h>
#include<string.h>
#include<errno.h>
void * func(void * arg)
{
int i=0;
while(1)
{
if(i==10)
{
int * p = (int *)malloc(sizeof(int));
*p=11;
pthread_exit(p);
}
printf("fun run %dn",i++);
sleep(1);
}
return NULL;
}
int main()
{
pthread_t t1,t2;
int err = pthread_create(&t1,NULL,func,NULL);
if(err!=0)
{
printf("thread_create Failed:%sn",strerror(errno));
}else{
printf("thread_create successn");
}
void *p=NULL;
pthread_join(t1,&p);
printf("线程退出:code=%d",*(int*)p);
return EXIT_SUCCESS;
}
void pthread_exit(void *arg);
pthread_exit函数的参数就跟正常线程结束return的使用时一样的,都会被等待它结束的主线程获取到。










