15a6d2c539f1cd59629c0e4f90d892d7339b40b5
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                 }
89         }
93         // critical section
94         store_32(&var, 2);
96         store_32(&turn, 0);
98         store_32(&flag1, false);
99 }
101 void p0l(void *a) {
102         int i;
103         for(i=0;i<PROBLEMSIZE;i++) {
104                 p0();
105         }
106 }
109 void p1l(void *a) {
110         int i;
111         for(i=0;i<PROBLEMSIZE;i++) {
112                 p1();
113         }
114 }
117 int user_main(int argc, char **argv)
118 {
119         thrd_t a, b;
121         store_32(&flag0, false);
123         store_32(&flag1, false);
125         store_32(&turn, 0);
127         thrd_create(&a, p0l, NULL);
128         thrd_create(&b, p1l, NULL);
130         thrd_join(a);
131         thrd_join(b);
133         return 0;
134 }