当前位置: C语言 -- 标准库 -- <threads.h> -- thrd_detach

thrd_detach函数


概要:
#include <threads.h>
int thrd_detach(thrd_t thr);

描述:

该函数将分离线程。该函数告诉操作系统在参数thr标识的线程结束时,处理分配给该线程的所有资源。调用该函数前,参数thr标识的线程应没有被分离或者和其它线程连接。

(注:分离线程只是告诉操作系统:线程结束后自动回收资源,其它线程不用等它;但进程结束会杀死所有线程,这是无法通过分离线程避免的。)


参数:
thrd_t thr

线程标识符。


返回值:

如果成功分离,函数返回thrd_success;如果不能成功分离,函数返回thrd_error。


范例:
1 
2 
3 
4 
5 
6 
7 
8 
9 
10 
11 
12 
13 
14 
15 
16 
17 
18 
19 
20 
21 
22 
23 
24 
25 
26 
27 
28 
29 
30 
31 
32 
33 
34 
35 
36 
37 
38 
39 
40 
41 
42 
/*函数thrd_detach范例*/

#ifdef __STDC_NO_THREADS__
#error "Implementation does not support multi-threads."
#endif

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

/*新线程中执行的函数。*/
int func(void *arg)
{
    /*执行代码。*/
    puts("The child thread has completed its task.");
    
    return 0;
}

int main(void)
{
    thrd_t threadId;
    
    /*创建线程。*/
    if(thrd_create(&threadId, func, NULL) != thrd_success)
    {
        perror("thrd_create error");
        exit(EXIT_FAILURE);
    }
    
    /*分离线程。*/
    if(thrd_detach(threadId) == thrd_success)
        puts("The thread has been detached.");
    else
        perror("thrd_detach error");
    
    thrd_sleep(&(struct timespec){.tv_sec = 5}, NULL);	//等待子线程结束。
    puts("The main thread will exit.");
    
    return 0;
}


输出:

The thread has been detached.

The child thread has completed its task.

The main thread will exit.


相关内容:
thrd_current 标识调用线程的函数。
thrd_sleep 暂停当前线程的函数。
thrd_equal 测试两个线程是否为同一线程的函数。
thrd_exit 终止当前线程的函数。
thrd_join 连接线程的函数。
thrd_create 创建线程的函数。
thrd_yield 让其它线程运行的函数。


主要参考资料:

1、ISO/IEC 9899:2024

2、ISO/IEC 9899:2018