2 * Dekker's critical section algorithm, implemented with fences.
5 * http://www.justsoftwaresolutions.co.uk/threading/
14 std::atomic<bool> flag0, flag1;
15 std::atomic<int> turn;
23 int val = *((int*)argv);
25 int otherTurn = 1 - val;
26 std::atomic<bool> *myFlag = val == 0 ? &flag0 : &flag1;
27 std::atomic<bool> *otherFlag = val == 0 ? &flag1 : &flag0;
28 myFlag->store(true, wildcard(1));
29 std::atomic_thread_fence(wildcard(2)); // seq_cst
31 while (otherFlag->load(wildcard(3)))
33 if (turn.load(wildcard(4)) != myTurn)
35 myFlag->store(false, wildcard(5));
36 while (turn.load(wildcard(6)) != myTurn)
40 myFlag->store(true, wildcard(7));
41 std::atomic_thread_fence(wildcard(8)); // seq_cst
45 std::atomic_thread_fence(wildcard(9)); // acquire
50 var1.store(1, std::memory_order_relaxed);
51 var2.load(std::memory_order_relaxed);
53 var2.store(2, std::memory_order_relaxed);
54 var1.load(std::memory_order_relaxed);
57 turn.store(otherTurn, wildcard(10));
58 std::atomic_thread_fence(wildcard(11)); // release
59 myFlag->store(false, wildcard(12));
68 int user_main(int argc, char **argv)
75 atomic_init(&var1, 0);
76 atomic_init(&var2, 0);
78 int thrd1 = 0, thrd2 = 1;
79 thrd_create(&a, p0, &thrd1);
80 thrd_create(&b, p1, &thrd2);