约 1118 字

约 6 分钟

#C 语言标准库函数 thrd_detach

/*********************************************
 * @brief 分离指定线程
 * @param th 要等分离的线程 ID
 * @return 是否成功
 ********************************************/
int thrd_detach(thrd_t th, int* res);

说明

将指定的线程分离,该线程退出后其占用的资源将自动释放。

参数

  • th - 要分离的线程

返回值

  • 成功时返回 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);

    // 分离线程
    thrd_detach(th);
    
    return 0;
}

#推荐阅读

#参考标准

  • C17 standard (ISO/IEC 9899:2018):
    • 7.26.5.3 The thrd_detach function (p: 280)
  • C11 standard (ISO/IEC 9899:2011):
    • 7.26.5.3 The thrd_detach function (p: 383-384)

更新: 2025/10/25

作者: PlanC

创建: 2025/8/22