PAYATHON 2026

C 的 thrd_start_t 返回值有什么用途,如何获取?

数据小陈

结论

thrd_start_t 是线程启动函数的类型。该函数返回一个 int,线程创建方可以调用 thrd_join,通过第二个参数读取这个返回值。

获取线程返回值

线程函数的签名是 int (*)(void *)。下面的例子中,工作线程将传入的整数乘以 2 后返回,调用 thrd_join 的线程再读取结果:

#include <stdio.h>
#include <threads.h>

int worker(void *arg)
{
    int value = *(int *)arg;
    return value * 2;
}

int main(void)
{
    thrd_t thread;
    int input = 21;
    int result;

    if (thrd_create(&thread, worker, &input) != thrd_success) {
        return 1;
    }

    if (thrd_join(thread, &result) != thrd_success) {
        return 1;
    }

    printf("thread result: %d\n", result); /* 42 */
    return 0;
}

thrd_join(thread, &result) 会等待线程结束。调用成功后,线程函数的返回值会写入 result。如果不需要读取结果,可以将第二个参数设为 NULL,函数仍会等待线程结束。

区分两种返回值

thrd_join 会返回一个状态码,用来表示 join 操作是否成功。这个状态码和线程函数返回的结果是两个不同的值。应先检查 join 是否成功,再使用 result。

如果需要取得线程结果,应在线程结束后调用 thrd_join。传给线程函数的参数也要在线程使用期间保持有效。上例中的 input 会一直有效,直到 main 返回。

备注:内容仅供参考。