2118

11 分钟

#C 语言标准库函数 thrd_create

/********************************************* * @brief 创建线程 * @param[out] th 返回线程 ID * @param func 线程入口函数指针 * @param args 传递给线程函数的参数 * @return 是否成功 ********************************************/ int thrd_create(thrd_t* th, thrd_start_t func, void* args);

说明

创建一个线程,线程以调用 func(args) 的方式运行,线程 ID 通过 th 参数返回。

这个函数的完成与线程的开始同步。

线程入口函数指针 func 的类型 thrd_start_tint(*)(void*)

线程入口函数的返回值即为线程的返回值,等价于以该值调用 thrd_exit 函数。

可以通过 thrd_join 函数等待线程结束并获取其返回值; 也可以通过 thrd_detach 函数分离线程(丢弃其返回值)。

线程创建后必须调用 thrd_jointhrd_detach 之一,否则该线程会持续占据资源。

参数

  • th - 返回线程 ID
  • func - 线程的入口函数指针,类型为 int(*)(void*)
  • args - 传递给线程函数 func 的参数;可以为 NULL 即没有参数

返回值

  • 成功时返回 thrd_success
  • 内存不足时返回 thrd_nomem
  • 其它错误返回 thrd_error

#示例

#include <stdio.h> #include <threads.h> // 定义线程参数结构 struct Args { char name[128]; int age; }; // 线程入口函数 int func(void* data) { struct Args* args = (struct Args*)data; printf("name:%s age:%d\n", args->name, args->age); return args->age + 1; // 返回 } int main(void) { struct Args args = {"Tom", 8}; // 创建线程 thrd_t th; thrd_create(&th, func, &args); // 等待线程结束 int ret; thrd_join(th, &ret); printf("线程返回值: %d\n", ret); return 0; }

运行结果:

name:Tom age:8 线程返值: 9

#推荐阅读

#参考标准

  • C17 standard (ISO/IEC 9899:2018):
    • 7.26.5.1 The thrd_create function (p: 279)
  • C11 standard (ISO/IEC 9899:2011):
    • 7.26.5.1 The thrd_create function (p: 383)

创建于 2025/8/22

更新于 2025/8/22