/*********************************************
* @brief 等待线程结束
* @param th 要等待的线程 ID
* @param[out] res 返回线程的返回值
* @return 是否成功
********************************************/
int thrd_join(thrd_t th, int* res);
!subtitle:说明
阻塞当前线程,直到目标线程结束,获取该线程的返回值。
这个函数的完成与线程的终止同步。
目标线程的返回值会保存到 res 指向的内存中。
不能等待同一个线程两次,也不能等待一个已经被 thrd_detach 分离的线程。
!subtitle:参数
th - 要等待的线程
res - 用于保存线程的返回值,可以为 NULL 即不接收返回值
!subtitle:返回值
成功时返回 thrd_success
失败时返回 thrd_error
#include <stdio.h>
#include <threads.h>
// 线程入口函数
int func(void* data)
{
return 10;
}
int main(void)
{
// 创建线程
thrd_t th;
thrd_create(&th, func, NULL);
// 等待线程结束
int ret;
thrd_join(th, &ret);
printf("线程返回值: %d\n", ret);
return 0;
}
运行结果:
线程返回值: 10
C17 standard (ISO/IEC 9899:2018):
7.26.5.6 The thrd_join function (p: 280-281)
C11 standard (ISO/IEC 9899:2011):
7.26.5.6 The thrd_join function (p: 384-385)