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

mtx_timedlock函数


概要:
#include <threads.h>
int mtx_timedlock(mtx_t * restrict mtx, const struct timespec * restrict ts);

描述:

该函数试图阻塞调用线程,直至加锁参数mtx指向的互斥,或者到达参数ts指定的超时时间(该时间为基于TIME_UTC的日历时间。)。参数mtx指向的互斥应支持超时,即类型应为mtx_timed或者mtx_timed | mtx_recursive类型。如果成功加锁互斥,对于同一互斥先前mtx_unlock函数的调用与该函数的操作同步。


参数:
mtx_t * restrict mtx

指向将被加锁的互斥的指针。

const struct timespec * restrict ts

指向struct timespec类型对象的指针。


返回值:

如果成功加锁互斥,函数返回thrd_success;如果到达参数ts指定的时间,还没有获得请求的资源,函数返回thrd_timedout;如果请求无法得到满足,函数返回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 
43 
44 
45 
46 
47 
48 
49 
50 
51 
52 
53 
54 
55 
56 
57 
58 
59 
60 
61 
62 
63 
64 
/*函数mtx_timedlock范例*/

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

#include <stdio.h>
#include <stdlib.h>
#include <threads.h>
 
#define TIME 5  //线程阻塞时间,单位:秒。

mtx_t mutex;

/*在新线程中执行的函数。*/
int func(void *arg)
{
    switch(mtx_timedlock(&mutex, (struct timespec *)arg))
    {
    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 main(void)
{
    thrd_t threadId;

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

    /*创建线程。*/
    if(thrd_create(&threadId, func, &(struct timespec){TIME, 0}) != thrd_success)
    {
        perror("thrd_create error");
        exit(EXIT_FAILURE);
    }

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

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

    return 0;
}


输出:

The function has successfully locked the mutex.

注:使用Pelles C编译。

这里(struct timespec){TIME, 0}是个复合字面量(compound literal)。


相关内容:
mtx_lock 加锁互斥的函数。
mtx_init 创建互斥的函数。
mtx_destroy 销毁互斥的函数。
mtx_trylock 尝试加锁互斥的函数。
mtx_unlock 解锁互斥的函数。