-
Notifications
You must be signed in to change notification settings - Fork 0
/
dekker.c
59 lines (48 loc) · 1.2 KB
/
dekker.c
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
#include <stdio.h>
#include <pthread.h>
#include <stdbool.h>
bool flag[2] = {false, false};
int turn = 0;
int nums = 0;
void* p0(void* whatevs) {
flag[0] = true;
while (__sync_synchronize(), flag[1] == true)
if (__sync_synchronize(), turn != 0) {
flag[0] = false;
while (__sync_synchronize(), turn != 0) {}
flag[0] = true;
}
// critical section
for (int i = 0; i < 512; i++)
nums += 1;
turn = 1;
__sync_synchronize();
flag[0] = false;
return NULL;
}
void* p1(void* whatevs) {
flag[1] = true;
while (__sync_synchronize(), flag[0] == true)
if (__sync_synchronize(), turn != 1) {
flag[1] = false;
while (__sync_synchronize(), turn != 1) {}
flag[1] = true;
}
// critical section
for (int i = 0; i < 512; i++)
nums -= 1;
turn = 0;
__sync_synchronize();
flag[1] = false;
return NULL;
}
int main(void) {
pthread_t th0, th1;
pthread_create(&th0, NULL, p0, 0);
pthread_create(&th1, NULL, p1, 0);
pthread_join(th0, NULL);
pthread_join(th1, NULL);
// should be 0 if correct
printf("Nums: %d\n", nums);
return nums;
}