国际访客建议访问 Primers 编程伙伴 国际版站点 > C 教程 > thrd_exit 以获得更好的体验。

# C 语言标准库函数 thrd_exit

在头文件 threads.h 中定义。
/*********************************************
 * @brief 退出当前线程
 * @param res 线程返回值
 ********************************************/
void thrd_exit(int res);

!subtitle:说明

退出当前线程。

主线程调用此函数时只会退出主线程本身而不会退出进程。

进程中的最后一个线程退出时,整个进程退出,进程返回值为 EXIT_SUCCESS

!subtitle:参数

  • res - 线程返回值

!subtitle:返回值

# 示例

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

// 线程入口函数
int func(void* data)
{
    // 阻塞 5 秒
    struct timespec duration = {
        .tv_sec = 5,
    }
    thrd_sleep(&duration, NULL);
    
    // 线程退出
    thrd_exit(1);
}

int main(void)
{
    // 创建线程
    thrd_t th;
    thrd_create(&th, func, NULL);
    
    // 主线程通过 thrd_exit 退出时,进程不会立刻退出
    thrd_exit(1);

    return 0;
}

# 推荐阅读

# 参考标准

  • C17 standard (ISO/IEC 9899:2018):

    • 7.26.5.8 The thrd_exit function (p: 281)

  • C11 standard (ISO/IEC 9899:2011):

    • 7.26.5.8 The thrd_exit function (p: 385)

本文 更新于: 2025-11-27 09:38:11 创建于: 2025-11-27 09:38:11