<pthread.h>头文件中,语法格式如下:
int pthread_join(pthread_t thread, void ** retval);thread 参数用于指定接收哪个线程的返回值;retval 参数表示接收到的返回值,如果 thread 线程没有返回值,又或者我们不需要接收 thread 线程的返回值,可以将 retval 参数置为 NULL。
再次强调,一个线程执行结束的返回值只能由一个 pthread_join() 函数获取,当有多个线程调用 pthread_join() 函数获取同一个线程的执行结果时,哪个线程最先执行 pthread_join() 函数,执行结果就由那个线程获得,其它线程的 pthread_join() 函数都将执行失败。以上这些宏都声明在 <errno.h> 头文件中,如果程序中想使用这些宏,需提前引入此头文件。
pthread_join(A,NULL);语句,可以轻松实现“及时释放线程 A 所占资源”的目的。
#include <stdio.h>
#include <errno.h> //使用宏 ESRCH
#include <pthread.h>
//线程执行的函数
void *ThreadFun(void *arg)
{
pthread_exit("http://c.biancheng.net");
}
int main()
{
int res;
void * thread_result;
pthread_t myThread;
//创建 myThread 线程
res = pthread_create(&myThread, NULL, ThreadFun, NULL);
if (res != 0) {
printf("线程创建失败");
return 0;
}
//阻塞主线程,等待 myThread 线程执行结束
res = pthread_join(myThread, &thread_result);
if (res != 0) {
printf("1:等待线程失败");
}
//输出获取到的 myThread 线程的返回值
printf("%s\n", (char*)thread_result);
//尝试再次获取 myThread 线程的返回值
res = pthread_join(myThread, &thread_result);
if (res == ESRCH) {
printf("2:等待线程失败,线程不存在");
}
return 0;
}
假设程序位于 thread.c 文件中,执行过程如下:
[root@localhost ~]# gcc thread.c -o thread.exe -lpthread
[root@localhost ~]# ./thread.exe
http://c.biancheng.net
2:等待线程失败,线程不存在
版权说明:Copyright © 广州松河信息科技有限公司 2005-2025 版权所有 粤ICP备16019765号
广州松河信息科技有限公司 版权所有