7 #define RW_LOCK_BIAS 0x00100000
8 #define WRITE_LOCK_CMP RW_LOCK_BIAS
10 /** Example implementation of linux rw lock along with 2 thread test
17 static inline int read_can_lock(rwlock_t *lock)
19 return atomic_load_explicit(&lock->lock, memory_order_relaxed) > 0;
22 static inline int write_can_lock(rwlock_t *lock)
24 return atomic_load_explicit(&lock->lock, memory_order_relaxed) == RW_LOCK_BIAS;
27 static inline void read_lock(rwlock_t *rw)
29 int priorvalue = atomic_fetch_sub_explicit(&rw->lock, 1, memory_order_acquire);
30 while (priorvalue <= 0) {
31 atomic_fetch_add_explicit(&rw->lock, 1, memory_order_relaxed);
33 priorvalue = atomic_load_explicit(&rw->lock, memory_order_relaxed);
38 priorvalue = atomic_fetch_sub_explicit(&rw->lock, 1, memory_order_acquire);
42 static inline void write_lock(rwlock_t *rw)
44 int priorvalue = atomic_fetch_sub_explicit(&rw->lock, RW_LOCK_BIAS, memory_order_acquire);
45 while (priorvalue != RW_LOCK_BIAS) {
46 atomic_fetch_add_explicit(&rw->lock, RW_LOCK_BIAS, memory_order_relaxed);
48 priorvalue = atomic_load_explicit(&rw->lock, memory_order_relaxed);
49 if (priorvalue == RW_LOCK_BIAS)
53 priorvalue = atomic_fetch_sub_explicit(&rw->lock, RW_LOCK_BIAS, memory_order_acquire);
57 static inline int read_trylock(rwlock_t *rw)
59 int priorvalue = atomic_fetch_sub_explicit(&rw->lock, 1, memory_order_acquire);
63 atomic_fetch_add_explicit(&rw->lock, 1, memory_order_relaxed);
67 static inline int write_trylock(rwlock_t *rw)
69 int priorvalue = atomic_fetch_sub_explicit(&rw->lock, RW_LOCK_BIAS, memory_order_acquire);
70 if (priorvalue == RW_LOCK_BIAS)
73 atomic_fetch_add_explicit(&rw->lock, RW_LOCK_BIAS, memory_order_relaxed);
77 static inline void read_unlock(rwlock_t *rw)
79 atomic_fetch_add_explicit(&rw->lock, 1, memory_order_release);
82 static inline void write_unlock(rwlock_t *rw)
84 atomic_fetch_add_explicit(&rw->lock, RW_LOCK_BIAS, memory_order_release);
90 static void a(void *obj)
93 for(i = 0; i < 2; i++) {
100 store_32(&shareddata,(unsigned int)i);
101 write_unlock(&mylock);
106 int user_main(int argc, char **argv)
109 atomic_init(&mylock.lock, RW_LOCK_BIAS);
111 thrd_create(&t1, (thrd_start_t)&a, NULL);
112 thrd_create(&t2, (thrd_start_t)&a, NULL);