blob: 83bf2b360a69e4f2be69bf7f1d7952dd42506ed2 (
plain)
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
|
#include "../kit/threads.h"
#define KIT_TEST_FILE condition_variable
#include "../kit/test.h"
typedef struct {
mtx_t m;
int in;
int out;
cnd_t send;
cnd_t receive;
int value;
} cnd_test_data_t;
static int cnd_test_run(void *p) {
cnd_test_data_t *data = (cnd_test_data_t *) p;
mtx_lock(&data->m);
data->value = 20;
data->out = 1;
mtx_unlock(&data->m);
cnd_broadcast(&data->send);
mtx_lock(&data->m);
if (data->in == 0)
cnd_wait(&data->receive, &data->m);
data->in = 0;
data->value = 22;
data->out = 1;
mtx_unlock(&data->m);
cnd_broadcast(&data->send);
return 0;
}
TEST("condition variable") {
int i;
int ok = 1;
for (i = 0; i < 10; i++) {
cnd_test_data_t data;
data.in = 0;
data.out = 0;
data.value = 0;
ok = ok && (mtx_init(&data.m, mtx_plain) == thrd_success);
ok = ok && (cnd_init(&data.send) == thrd_success);
ok = ok && (cnd_init(&data.receive) == thrd_success);
thrd_t t;
ok = ok && (thrd_create(&t, cnd_test_run, &data) == thrd_success);
ok = ok && (mtx_lock(&data.m) == thrd_success);
if (data.out == 0)
ok = ok && (cnd_wait(&data.send, &data.m) == thrd_success);
data.out = 0;
int x = data.value;
data.in = 1;
ok = ok && (mtx_unlock(&data.m) == thrd_success);
ok = ok && (cnd_broadcast(&data.receive) == thrd_success);
ok = ok && (mtx_lock(&data.m) == thrd_success);
if (data.out == 0)
ok = ok && (cnd_wait(&data.send, &data.m) == thrd_success);
data.out = 0;
x += data.value;
ok = ok && (mtx_unlock(&data.m) == thrd_success);
ok = ok && (thrd_join(t, NULL) == thrd_success);
mtx_destroy(&data.m);
cnd_destroy(&data.send);
cnd_destroy(&data.receive);
ok = ok && (x == 42);
}
REQUIRE(ok);
}
#undef KIT_TEST_FILE
|