1 /*
2  * Dekker's critical section algorithm, implemented with fences.
3  * Translated to C by Patrick Lam <prof.lam@gmail.com>
4  *
5  * URL:
7  */
10 #include <stdbool.h>
11 #include "libinterface.h"
13 /* atomic */ int flag0, flag1;
14 /* atomic */ int turn;
16 #define true 1
17 #define false 0
18 #define NULL 0
20 /* uint32_t */ int var = 0;
22 void p0() {
23         store_32(&flag0, true);
26         int f1, t;
27         while (true)
28         {
30                 if (!f1) {
31                         break;
32                 }
37                 if (t) {
38                         store_32(&flag0, false);
39                         while(1) {
41                                 if (!t) {
42                                         break;
43                                 }
45                                 MC2_yield();
46                         }
48                         store_32(&flag0, true);
49                 } else {
50                         MC2_yield();
51                 }
52         }
56         // critical section
57         store_32(&var, 1);
59         store_32(&turn, 1);
61         store_32(&flag0, false);
62 }
64 void p1() {
65         store_32(&flag1, true);
68         int f0, t;
69         while (true) {
71                 if (!f0) {
72                         break;
73                 }
77                 if (!t) {
78                         store_32(&flag1, false);
79                         while (1) {
81                                 if (t)
82                                         break;
83                                 MC2_yield();
84                         }
86                         store_32(&flag1, true);
88                 } else {
89                         MC2_yield();
90                 }
91         }
95         // critical section
96         store_32(&var, 2);
98         store_32(&turn, 0);
100         store_32(&flag1, false);
101 }
103 void p0l(void *a) {
104         int i;
105         for(i=0;i<PROBLEMSIZE;i++) {
106                 p0();
107         }
108 }
111 void p1l(void *a) {
112         int i;
113         for(i=0;i<PROBLEMSIZE;i++) {
114                 p1();
115         }
116 }
119 int user_main(int argc, char **argv)
120 {
121         thrd_t a, b;
123         store_32(&flag0, false);
125         store_32(&flag1, false);
127         store_32(&turn, 0);
129         thrd_create(&a, p0l, NULL);
130         thrd_create(&b, p1l, NULL);
132         thrd_join(a);
133         thrd_join(b);
135         return 0;
136 }