pthread_join函数负责线程的回收,回收系统分配的资源,主要是线程pcb。pthread_join的功能和waitpid类似。
pthread_join 的函数原型如下:
int pthread_join(pthread_t thread, void **retval);
第一个参数是线程的id号
线程退出时使用pthead_exit()函数,返回退出状态。第二个参数获取线程的退出状态,由于pthead_exit(void *),所以为了获取返回值,需要使用二级指针去获取。如果不关心返回值,可以将第二个参数置为NULL
下面是pthread_join的用法,既可以传递数值,也可以传递结构体
#include "apue.h"
#include <pthread.h>
typedef struct {
int val;
char name[64];
}retval;
void *
mpthread1(void * arg)
{
printf("this is my first thread,pread_t is %lu\n",pthread_self());
pthread_exit((void*)2);
}
void *
mpthread2(void *arg)
{
printf("this is my second thread,pread_t is %lu\n",pthread_self());
retval *p = (retval *)malloc(sizeof(retval));
if( p == NULL)
pthread_exit((void *) p);
p->val = 100;
char buf[24] = "hello world";
strncpy(p->name,buf,strlen(buf));