標籤:skynet rw_lock __sync_synchronize
skynet 利用內建的原子操作來實現的一個讀寫鎖,重點是理解 ”full memory barrier“ ,UNPv2 中利用互斥和條件變數實現的讀寫鎖。前者是在硬體支援的情況下,顯得簡單明了,站的層次不一樣。
源碼貼出來:
struct rwlock {int write;int read;};static inline voidrwlock_init(struct rwlock *lock) {lock->write = 0;lock->read = 0;}static inline voidrwlock_rlock(struct rwlock *lock) {for (;;) {// isuued a full memory barrier. This typically means that operations issued // prior to the barrier are guaranteed to be performed before operations issued after the barrier.while(lock->write) {__sync_synchronize();}__sync_add_and_fetch(&lock->read,1);// 在給nreaders + 1 之後再次檢查是否有寫入者,有的話此次讀鎖請求失敗if (lock->write) {__sync_sub_and_fetch(&lock->read,1);} else {break;}}}static inline voidrwlock_wlock(struct rwlock *lock) {// 如果沒有寫者,__sync_lock_test_and_set會返回0,表示此次請求寫鎖成功;// 否則表示有其它寫者,則空轉while (__sync_lock_test_and_set(&lock->write,1)) {}// 在開始寫入之前發現有讀者進入,則要等到前面的操作完成while(lock->read) {__sync_synchronize();}}static inline voidrwlock_wunlock(struct rwlock *lock) {__sync_lock_release(&lock->write);}static inline voidrwlock_runlock(struct rwlock *lock) {__sync_sub_and_fetch(&lock->read,1);}
寫個簡單的程式跑下:
skynet源碼學習 - 讀寫鎖