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

thrd_timedout枚举常量


概要:
    enum {
        thrd_success = value,   //value值由实现定义。
        thrd_nomem = value,     //value值由实现定义。
        thrd_timedout = value,  //value值由实现定义。
        thrd_busy = value,      //value值由实现定义。
        thrd_error = value      //value值由实现定义。
     };

描述:

该枚举常量由超时等待函数返回,表示到达指定时间,函数还没有获得请求的资源。


Pelles C编译器<threads.h>头文件中,此类返回代码定义如下:

    enum {
        thrd_success = 0,   
        thrd_error = 1,     
        thrd_busy = 2,  
        thrd_nomem = 3,      
        thrd_timedout = 4      
     };

范例:
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 
43 
44 
45 
46 
47 
48 
49 
50 
51 
52 
53 
54 
55 
56 
57 
58 
59 
60 
61 
62 
63 
64 
65 
66 
67 
68 
69 
70 
71 
72 
73 
74 
75 
76 
77 
78 
79 
80 
81 
82 
/*枚举常量thrd_timedout范例*/

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

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

mtx_t mutex;

/*在新线程中执行的函数一。*/
int funcOne(void *arg)
{
    thrd_sleep(&(struct timespec){*((int *)arg)-4, 0}, NULL);

    switch(mtx_timedlock(&mutex, &(struct timespec){*((int *)arg), 0}))
    {
    case thrd_timedout:
        puts("The specified waiting time has elapsed.");
        thrd_exit(thrd_timedout);
    case thrd_error:
        perror("thrd_error");
        thrd_exit(thrd_error);
    default:
        puts("The function has successfully locked the mutex.");
        break;
    }

    /*其它代码。*/

    mtx_unlock(&mutex);

    thrd_exit(0);
}

/*在新线程中执行的函数二。*/
int funcTwo(void *arg)
{
    mtx_lock(&mutex);
    thrd_sleep(&(struct timespec){*((int *)arg)+5, 0}, NULL);
    mtx_unlock(&mutex);

    thrd_exit(0);
}

int main(void)
{
    thrd_t threadOne, threadTwo;
    int duration = 5;

    /*初始化互斥。*/
    if(mtx_init(&mutex, mtx_timed) != thrd_success)
    {
        perror("mtx_init");
        exit(EXIT_FAILURE);
    }

    /*创建线程。*/
    if(thrd_create(&threadOne, funcOne, &duration) != thrd_success)
    {
        perror("thrd_create");
        exit(EXIT_FAILURE);
    }

    if(thrd_create(&threadTwo, funcTwo, &duration) != thrd_success)
    {
        perror("thrd_create");
        exit(EXIT_FAILURE);
    }

    /*连接线程。*/
    thrd_join(threadOne, NULL);
    thrd_join(threadTwo, NULL);

    /*销毁互斥。*/
    mtx_destroy(&mutex);
    
    return 0;
}


输出:

The specified waiting time has elapsed.

注:使用Pelles C编译。

在这个例子中,创建了两个新线程;第一个线程中通过调用thrd_sleep函数使线程暂停1秒,第二个线程加锁了互斥;第二个线程加锁互斥后暂停10秒,第一个线程调用mtx_timedlock函数尝试加锁互斥,设定的时间是5秒;由于在设定时间内无法加锁互斥,mtx_timedlock函数返回thrd_timedout


相关内容:
thrd_success 表示操作成功的枚举常量。
thrd_nomem 表示因无法分配内存而操作失败的枚举常量。
thrd_busy 表示因请求资源已在使用而操作失败的枚举常量。
thrd_error 表示操作失败的枚举常量。