5 // #include <stdatomic.h>
9 #define RW_LOCK_BIAS 0x00100000
10 #define WRITE_LOCK_CMP RW_LOCK_BIAS
12 /** Example implementation of linux rw lock along with 2 thread test
19 static inline void read_lock(rwlock_t *rw)
21 int priorvalue = rw->lock.fetch_sub(1, memory_order_acquire);
22 while (priorvalue <= 0) {
23 rw->lock.fetch_add(1, memory_order_relaxed);
24 while (rw->lock.load(memory_order_relaxed) <= 0) {
27 priorvalue = rw->lock.fetch_sub(1, memory_order_acquire);
31 // Injected bug for the two fetch_sub ***
32 static inline void write_lock(rwlock_t *rw)
34 int priorvalue = rw->lock.fetch_sub(RW_LOCK_BIAS, memory_order_relaxed); // Should be acquire
35 while (priorvalue != RW_LOCK_BIAS) {
36 rw->lock.fetch_add(RW_LOCK_BIAS, memory_order_relaxed);
37 while (rw->lock.load(memory_order_relaxed) != RW_LOCK_BIAS) {
40 priorvalue = rw->lock.fetch_sub(RW_LOCK_BIAS, memory_order_relaxed); // Should be acquire
44 static inline void read_unlock(rwlock_t *rw)
46 rw->lock.fetch_add(1, memory_order_release);
49 static inline void write_unlock(rwlock_t *rw)
51 rw->lock.fetch_add(RW_LOCK_BIAS, memory_order_release);
55 atomic_int data1, data2;
60 for(i = 0; i < 4; i++) {
63 int d1 = data1.load(memory_order_relaxed);
64 int d2 = data2.load(memory_order_relaxed);
69 data1.store(i, memory_order_relaxed);
70 data2.store(i, memory_order_relaxed);
71 write_unlock(&mylock);
78 int main(int argc, char **argv)
81 mylock.lock.store(RW_LOCK_BIAS);
83 pthread_create(&t1, NULL, &a, NULL);
84 pthread_create(&t2, NULL, &a, NULL);
85 pthread_create(&t3, NULL, &a, NULL);
87 pthread_join(t1, NULL);
88 pthread_join(t2, NULL);
89 pthread_join(t3, NULL);