skynet源碼學習 - 讀寫鎖

來源:互聯網
上載者:User

標籤: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源碼學習 - 讀寫鎖

聯繫我們

該頁面正文內容均來源於網絡整理,並不代表阿里雲官方的觀點,該頁面所提到的產品和服務也與阿里云無關,如果該頁面內容對您造成了困擾,歡迎寫郵件給我們,收到郵件我們將在5個工作日內處理。

如果您發現本社區中有涉嫌抄襲的內容,歡迎發送郵件至: info-contact@alibabacloud.com 進行舉報並提供相關證據,工作人員會在 5 個工作天內聯絡您,一經查實,本站將立刻刪除涉嫌侵權內容。

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.