Commit state of repository at time of OOPSLA 2015 submission.
[satcheck.git] / benchmarks / cdschecker / linuxrwlock / linuxrwlocks.c.in
1 #include <stdio.h>
2 #include <threads.h>
3 #include <stdatomic.h>
4
5 #include "librace.h"
6
7 #define RW_LOCK_BIAS            0x00100000
8 #define WRITE_LOCK_CMP          RW_LOCK_BIAS
9
10 /** Example implementation of linux rw lock along with 2 thread test
11  *  driver... */
12
13 typedef union {
14         atomic_int lock;
15 } rwlock_t;
16
17 static inline int write_trylock(rwlock_t *rw)
18 {
19         int priorvalue = atomic_fetch_sub_explicit(&rw->lock, RW_LOCK_BIAS, memory_order_seq_cst);
20         if (priorvalue == RW_LOCK_BIAS)
21                 return 1;
22
23         atomic_fetch_add_explicit(&rw->lock, RW_LOCK_BIAS, memory_order_seq_cst);
24         return 0;
25 }
26
27 static inline void write_unlock(rwlock_t *rw)
28 {
29         atomic_fetch_add_explicit(&rw->lock, RW_LOCK_BIAS, memory_order_seq_cst);
30 }
31
32 rwlock_t mylock;
33 int shareddata;
34
35 static void a(void *obj) {
36         int i;
37         for(i = 0; i < PROBLEMSIZE; i++) {
38                 if (write_trylock(&mylock)) {
39                         write_unlock(&mylock);
40                 }
41         }
42 }
43
44 int user_main(int argc, char **argv)
45 {
46         thrd_t t1, t2;
47         atomic_init(&mylock.lock, RW_LOCK_BIAS);
48
49         thrd_create(&t1, (thrd_start_t)&a, NULL);
50         thrd_create(&t2, (thrd_start_t)&a, NULL);
51
52         thrd_join(t1);
53         thrd_join(t2);
54
55         return 0;
56 }