changes to seqlock
[model-checker-benchmarks.git] / seqlock / seqlock-wildcard.h
1 #include <stdatomic.h>
2 #include <threads.h>
3
4 #include "wildcard.h"
5
6 typedef struct seqlock {
7         // Sequence for reader consistency check
8         atomic_int _seq;
9         // It needs to be atomic to avoid data races
10         atomic_int _data;
11
12         seqlock() {
13                 atomic_init(&_seq, 0);
14                 atomic_init(&_data, 0);
15         }
16
17         int read() {
18                 while (true) {
19                         int old_seq = _seq.load(wildcard(1)); // acquire
20                         if (old_seq % 2 == 1) continue;
21
22                         int res = _data.load(wildcard(2)); // acquire
23                         if (_seq.load(wildcard(3)) == old_seq) { // relaxed
24                                 return res;
25                         }
26                 }
27         }
28         
29         void write(int new_data) {
30                 int old_seq = _seq.load(wildcard(4)); // acquire
31                 while (true) {
32                         if (old_seq % 2 == 1)
33                                 continue; // Retry
34
35                         // Should be relaxed!!! 
36                         if (_seq.compare_exchange_strong(old_seq, old_seq + 1,
37                                 wildcard(5), wildcard(6))) // relaxed 
38                                 break;
39                 }
40
41                 // Update the data
42                 _data.store(new_data, wildcard(7)); // release
43
44                 _seq.fetch_add(1, wildcard(8)); // release
45         }
46
47 } seqlock_t;