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);
32 while (atomic_load_explicit(&rw->lock, memory_order_relaxed) <= 0) {
35 priorvalue = atomic_fetch_sub_explicit(&rw->lock, 1, memory_order_acquire);
39 static inline void write_lock(rwlock_t *rw)
41 int priorvalue = atomic_fetch_sub_explicit(&rw->lock, RW_LOCK_BIAS, memory_order_acquire);
42 while (priorvalue != RW_LOCK_BIAS) {
43 atomic_fetch_add_explicit(&rw->lock, RW_LOCK_BIAS, memory_order_relaxed);
44 while (atomic_load_explicit(&rw->lock, memory_order_relaxed) != RW_LOCK_BIAS) {
47 priorvalue = atomic_fetch_sub_explicit(&rw->lock, RW_LOCK_BIAS, memory_order_acquire);
51 static inline int read_trylock(rwlock_t *rw)
53 int priorvalue = atomic_fetch_sub_explicit(&rw->lock, 1, memory_order_acquire);
57 atomic_fetch_add_explicit(&rw->lock, 1, memory_order_relaxed);
61 static inline int write_trylock(rwlock_t *rw)
63 int priorvalue = atomic_fetch_sub_explicit(&rw->lock, RW_LOCK_BIAS, memory_order_acquire);
64 if (priorvalue == RW_LOCK_BIAS)
67 atomic_fetch_add_explicit(&rw->lock, RW_LOCK_BIAS, memory_order_relaxed);
71 static inline void read_unlock(rwlock_t *rw)
73 atomic_fetch_add_explicit(&rw->lock, 1, memory_order_release);
76 static inline void write_unlock(rwlock_t *rw)
78 atomic_fetch_add_explicit(&rw->lock, RW_LOCK_BIAS, memory_order_release);
84 static void a(void *obj)
87 for(i = 0; i < 2; i++) {
94 store_32(&shareddata,(unsigned int)i);
95 write_unlock(&mylock);
100 int user_main(int argc, char **argv)
103 atomic_init(&mylock.lock, RW_LOCK_BIAS);
105 thrd_create(&t1, (thrd_start_t)&a, NULL);
106 thrd_create(&t2, (thrd_start_t)&a, NULL);