1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 | #define WAFLAG 1 #define RC_INCR 2 typedef struct { atomic_t rdr_cnt_and_flag __cacheline_aligned_in_smp; atomic_t writer_requests __cacheline_aligned_in_smp; atomic_t writer_completions __cacheline_aligned_in_smp; } rwlock_t; void init_lock(rwlock_t *lock) { lock->rdr_cnt_and_flag = ATOMIC_INIT(0); lock->writer_requests = ATOMIC_INIT(0); lock->writer_completions = ATOMIC_INIT(0); } void reader_lock(rwlock_t *lock) { while (atomic_read(&lock->writer_completions) != //(a) atomic_read(&lock->writer_requests)) cpu_relax(); atomic_add(RC_INCR, &lock->rdr_cnt_and_flag); //(b) while ((atomic_read(&lock->rdr_cnt_and_flag) & WAFLAG) != 0)//(c) cpu_relax(); } void reader_unlock(rwlock_t *lock) { atomic_sub(RC_INCR, &lock->rdr_cnt_and_flag); //(d) } void writer_lock(rwlock_t *lock) { int id = atomic_inc_return(&lock->writer_requests); //(e) while (atomic_read(&lock->writer_completions) != id) //(f) cpu_relax(); while (atomic_cmpxchg(&lock->rdr_cnt_and_flag, 0, WAFLAG) != 0)//(g) while (atomic_read(&lock->rdr_cnt_and_flag) != 0) cpu_relax(); } void writer_unlock(rwlock_t *lock) { atomic_dec(&lock->rdr_cnt_and_flag); //(h) lock->writer_completions.counter++; //(i) } |
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 | typedef struct { atomic_t requests __cacheline_aligned_in_smp; atomic_t completions __cacheline_aligned_in_smp; atomic_t nr_readers __cacheline_aligned_in_smp; } rwlock_t; void init_lock(rwlock_t *lock) { lock->requests = ATOMIC_INIT(0); lock->completions = ATOMIC_INIT(0); lock->nr_readers = ATOMIC_INIT(0); } void reader_lock(rwlock_t *lock) { int id = atomic_inc_return(&lock->requests); //(a) while (atomic_read(&lock->completions) != id) //(b) cpu_relax(); atomic_inc(&lock->nr_readers); //(c) lock->completions.counter++; //(d) } void reader_unlock(rwlock_t *lock) { atomic_dec(&lock->nr_readers); //(e) } void writer_lock(rwlock_t *lock) { int id = atomic_inc_return(&lock->requests); //(f) while (atomic_read(&lock->completions) != id) //(g) cpu_relax(); while (atomic_read(&lock->nr_readers) > 0) //(h) cpu_relax(); } void writer_unlock(rwlock_t *lock) { lock->completions.counter++; //(i) } |
欢迎光临 电子技术论坛_中国专业的电子工程师学习交流社区-中电网技术论坛 (http://bbs.eccn.com/) | Powered by Discuz! 7.0.0 |