mtx_recursive枚举常量
概要:
enum {
mtx_plain = value, //value值由实现定义。
mtx_recursive = value, //value值由实现定义。
mtx_timed = value //value值由实现定义。
};
描述:
该枚举常量用作mtx_init函数的参数,创建一个支持递归加锁的互斥对象。
在Pelles C编译器<threads.h>头文件中,互斥类型定义如下:
enum {
mtx_plain = 0x01,
mtx_timed = 0x02,
mtx_recursive = 0x10
};
范例:
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
|
/*枚举常量mtx_recursive范例*/
#ifdef __STDC_NO_THREADS__
#error "Implementation does not support multi-threads."
#endif
#include <stdio.h>
#include <stdlib.h>
#include <threads.h>
#define NUMBER 5
mtx_t mutex;
/*计算阶乘的函数。*/
int factorial(int arg)
{
mtx_lock(&mutex);
if(arg == 1)
return 1;
else
return arg*factorial(arg-1);
mtx_unlock(&mutex);
}
/*新线程中执行的函数。*/
int func(void *arg)
{
thrd_exit(factorial(*(int *)arg));
}
int main(void)
{
thrd_t threadId;
int result;
/*创建互斥。*/
if(mtx_init(&mutex, mtx_plain | mtx_recursive) != thrd_success)
{
perror("mtx_init error");
exit(EXIT_FAILURE);
}
/*创建线程。*/
if(thrd_create(&threadId, func, &(int){NUMBER}) != thrd_success)
{
perror("thrd_create error");
exit(EXIT_FAILURE);
}
/*连接线程。*/
thrd_join(threadId, &result);
printf("The factorial of %d is %d.\n", NUMBER, result);
/*销毁互斥。*/
mtx_destroy(&mutex);
return 0;
}
|
输出:
The factorial of 5 is 120.
注:使用Pelles C编译。
相关内容: