thrd_detach

来自cppreference.com
< c‎ | thread
在标头 <threads.h> 定义
int thrd_detach(thrd_t thr );
(C11 起)

thr 所标识的线程从当前环境中分离。一旦该线程退出,就自动释放其保有的资源。如果线程非分离状态则需要 join 等待线程结束,否则会产生一个僵尸线程。

目录

[编辑]参数

thr - 要分离的线程的标识符

[编辑]返回值

若成功则为 thrd_success,否则为 thrd_error

[编辑]僵尸线程产生的示例

#include<stdio.h>#include<stdint.h>#include<threads.h>   int test_fn(void*arg){return0;}   int test_detach_fn(void*arg){ thrd_detach(thrd_current());return0;}   int main(){thrd_t th;int16_t i =0;int ret =0;int32_t status =0;   // 循环创建线程,但是不等待线程结束,但分离线程。for(i =0; i <INT16_MAX;++i){ status =thrd_create(&th, test_detach_fn, NULL);   if(status !=thrd_success){printf("detach fail %d\n", i);break;}   }   // 循环创建线程,但是等待线程结束,但不分离线程。for(i =0; i <INT16_MAX;++i){ status =thrd_create(&th, test_fn, NULL);   if(status !=thrd_success){printf("join nodetach fail %d\n", i);break;}   thrd_join(th, &ret);   }   // 循环创建线程,但是不等待线程结束,也不分离线程。for(i =0; i <INT16_MAX;++i){ status =thrd_create(&th, test_fn, NULL);   if(status !=thrd_success){printf("nodetach fail %d\n", i);break;}   }   return0;}     /* 如果你尝试用 gcc 编译,记得链接线程库 gcc xx.c -o xx -lpthread */

输出:

nodetach fail 32754

[编辑]引用

  • C17 标准(ISO/IEC 9899:2018):
  • 7.26.5.3 The thrd_detach function (第 280 页)
  • C11 标准(ISO/IEC 9899:2011):
  • 7.26.5.3 The thrd_detach function (第 383-384 页)

[编辑]参阅

阻塞到线程终止为止
(函数)[编辑]
detach 的 C++ 文档
close