1、函数原型
int pthread_join(pthread_t pid, void **value_ptr);
- pid:所等待的线程ID;
- value_ptr:通常设置为NULL,如果不为NULL,pthread_join将复制一份线程退出值到一个内存区域,并让*value_ptr指向该内存。
- 返回值:执行成功返回0,否则返回错误码。
2、作用
pthread_creat创建完成子线程后,主线程与子线程并行执行,用pthread_join可以让主线程等待子线程结束后再继续执行。
pthread_join用于等待子线程执行结束,即子线程函数执行完毕才会返回,会一直阻塞。
主线程调用pthread_join后,主线程会挂起,让出CPU直到该子线程执行结束。调用pthread_join让子线程执行结束后,子线程资源会自动释放。
3、示例
#include <pthread.h>
#include <stdio.h>void thread_func(void)
{int i;for(i = 0; i < 3; i++){printf("thread cur cnt:%d\n",i);}printf("thread_func exit\n");return;
}
int main(int argc,char *argv[])
{pthread_t thrid;int ret;ret = thread_creat(&thrid,NULL,(void *(*)(void *))thread_func,NULL);if(ret){printf("pthread creat error:%d\n",ret);return -1;}pthread_join(thrid,NULL);return 0;
}