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

thrd_exit函数


概要:
#include <threads.h>
_Noreturn void thrd_exit(int res);

描述:

该函数终止调用线程的执行。

对于每个使用非空析构函数创建、并且值为非空值的线程专属存储密匙,thrd_exit函数将与密匙关联的值设置为空指针,然后使用其先前值调用析构函数。析构函数的调用顺序是不明确的。如果此过程后,仍然存在具有非空析构函数和值的密匙,实现将重复此过程,最多可以重复TSS_DTOR_ITERATIONS次。

此后thrd_exit函数终止调用线程的执行,并将调用线程的结果代码设置为参数res。最后一个线程终止后,程序正常终止。这种行为就好像程序在线程终止时调用了exit(EXIT_SUCCESS)


参数:
int res

int类型整数。


返回值:

无。


范例:
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 
/*函数thrd_exit范例*/

#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((char *)arg);
    
    thrd_exit(0);
}

int main(void)
{
    thrd_t threadId;
    char arr[] = "This is a new thread.";
    
    /*创建线程。*/
    if(thrd_create(&threadId, func, arr) != thrd_success)
    {
        perror("thrd_create error");
        exit(EXIT_FAILURE);
    }

    /*连接线程。*/
    thrd_join(threadId, NULL);
    
    return 0;
}


输出:

This is a new thread.

注:使用Pelles C编译。

这里两个thrd_exit(0);语句分别终止新线程的执行和主线程的执行。


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