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
指向const 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
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
|
/*函数mtx_timedlock范例*/
#ifdef __STDC_NO_THREADS__
#error "Implementation does not support multi-threads."
#endif
#include <stdio.h>
#include <stdlib.h>
#include <threads.h>
#define TIMEOUT 5 //超时时间5秒。
mtx_t mutex;
/*尝试锁定互斥锁的子线程函数。*/
int func(void *arg)
{
struct timespec ts;
/*计算绝对超时时间。*/
timespec_get(&ts, TIME_UTC);
ts.tv_sec += TIMEOUT;
printf("Child thread: Attempt to lock the mutex and wait for %d seconds.\n", TIMEOUT);
int ret = mtx_timedlock(&mutex, &ts);
if(ret==thrd_timedout)
{
puts("Child thread: The time specified was reached without acquiring the requested resource.");
return thrd_timedout;
}
else if(ret==thrd_error)
{
puts("Child thread: The request to acquire the mutex lock could not be honored.");
return thrd_error;
}
else
{
puts("Child thread: Successfully acquired the mutex lock.The data is being processed...");
mtx_unlock(&mutex);
puts("Child thread: Released the mutex.");
return 0;
}
}
int main(void)
{
thrd_t threadId;
/*初始化支持超时的互斥。*/
if(mtx_init(&mutex, mtx_timed) != thrd_success)
{
fprintf(stderr, "The request to create a mutex object could not be honored.");
exit(EXIT_FAILURE);
}
/*主线程先锁定互斥。*/
if(mtx_lock(&mutex) != thrd_success)
{
fprintf(stderr, "Failed to lock mutex.\n");
mtx_destroy(&mutex);
exit(EXIT_FAILURE);
}
puts("Main thread: Acquired the mutex.");
/*创建子线程。*/
if(thrd_create(&threadId, func, NULL) != thrd_success)
{
perror("thrd_create");
exit(EXIT_FAILURE);
}
/*主线程2秒后释放互斥。*/
puts("Main thread: The mutex will be released in 2 seconds.");
thrd_sleep(&(struct timespec){.tv_sec = 2}, NULL);
mtx_unlock(&mutex);
puts("Main thread: Released the mutex.");
/*连接线程。*/
thrd_join(threadId, NULL);
/*销毁互斥。*/
mtx_destroy(&mutex);
return 0;
}
|
输出:
Main thread: Acquired the mutex.
Main thread: The mutex will be released in 2 seconds.
Child thread: Attempt to lock the mutex and wait for 5 seconds.
Main thread: Released the mutex.
Child thread: Successfully acquired the mutex lock.The data is being processed...
Child thread: Released the mutex.
相关内容:
主要参考资料:
1、ISO/IEC 9899:2024
2、ISO/IEC 9899:2018