这里写目录标题
pthread_join函数
int pthread_join(pthread_t pthread, void *retval)
参数:
pthread:要回收的子线程的ID
retval:读取线程退出的携带信息
传出参数
void ptr;
pthread_join(pthid,&ptr);
指向的内存和pthread_exit参数指向地址一致
代码
#include <stdio.h>
#include <pthread.h>
#include <unistd.h>
void *pthread1(void * arc)
{
printf("pthread1 is running\n");
printf("pthread1 id is %ld",pthread_self());
pthread_exit("pthread is exit\n");
}
void main()
{
pthread_t id;
pthread_create(&id,NULL,pthread1,NULL);
printf("main pthread is %ld\n",pthread_self());
void * ptr=NULL;
pthread_join(id,&ptr);
printf("join : ptr is %s\n",(char *)ptr);
int i=0;
while(i<10)
{
printf("main pthread is running %d\n",i);
i++;
sleep(1);
}
}
~
执行结果
注意的一些细节:
函数原型: void pthread‐exit(void *retval);
retval指针:必须指向全局,堆,静态变量
如果该代码改成:
#include <stdio.h>
#include <pthread.h>
#include <unistd.h>
void *pthread1(void * arc)
{
printf("pthread1 is running\n");
printf("pthread1 id is %ld\n",pthread_self());
int num=10;
//pthread_exit("pthread is exit\n");
pthread_exit((void * )&num);
}
void main()
{
pthread_t id;
pthread_create(&id,NULL,pthread1,NULL);
printf("main pthread is %ld\n",pthread_self());
//void * ptr=NULL;
//pthread_join(id,&ptr);
//printf("join : ptr is %s\n",(char *)ptr);
void * ptr=NULL;
pthread_join(id,&ptr);
printf("join : ptr is %d\n",*(int *)ptr);
int i=0;
while(i<10)
{
printf("main pthread is running %d\n",i);
i++;
sleep(1);
}
}
执行结果:
可以看到这里ptr不是10
这是因为这里的num是存放在栈区的,所以会出现错误。