Commit state of repository at time of OOPSLA 2015 submission.
[satcheck.git] / benchmarks / cdschecker / dekker / dekker-fences.cc.in
1 /*
2  * Dekker's critical section algorithm, implemented with fences.
3  *
4  * URL:
5  *   http://www.justsoftwaresolutions.co.uk/threading/
6  */
7
8 #include <atomic>
9 #include <threads.h>
10
11 #include "librace.h"
12
13 std::atomic<bool> flag0, flag1;
14 std::atomic<int> turn;
15 std::atomic<int> var;
16
17 void p0() {
18         flag0.store(true);
19
20         while (flag1.load()) {
21                 if (turn.load() !=0)
22                 {
23                         flag0.store(false);
24                         while (turn.load() != 0) {
25                                 thrd_yield();
26                         }
27                         flag0.store(true);
28                 } else
29                         thrd_yield();
30         }
31
32         // critical section
33         var.store(1);
34
35         turn.store(1);
36         flag0.store(false);
37 }
38
39 void p1() {
40         flag1.store(true);
41
42         while (flag0.load()) {
43                 if (turn.load() != 1) {
44                         flag1.store(false);
45                         while (turn.load() != 1) {
46                                 thrd_yield();
47                         }
48                         flag1.store(true);
49                 } else
50                         thrd_yield();
51         }
52         
53         // critical section
54         var.store(2);
55
56         turn.store(0);
57         flag1.store(false);
58 }
59
60 void p0l(void *arg) {
61         int i;
62         for(i=0;i<PROBLEMSIZE;i++)
63                 p0();
64 }
65
66 void p1l(void *arg) {
67         int i;
68         for(i=0;i<PROBLEMSIZE;i++)
69                 p1();
70 }
71
72 int user_main(int argc, char **argv)
73 {
74         thrd_t a, b;
75
76         flag0 = false;
77         flag1 = false;
78         turn = 0;
79         var=0;
80         
81         thrd_create(&a, p0l, NULL);
82         thrd_create(&b, p1l, NULL);
83
84         thrd_join(a);
85         thrd_join(b);
86
87         return 0;
88 }