skynet源码学习 - 读写锁
struct rwlock { int write; int read; }; static inline void rwlock_init(struct rwlock *lock) { lock->write = 0; lock->read = 0; } static inline void rwlock_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 void rwlock_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 void rwlock_wunlock(struct rwlock *lock) { __sync_lock_release(&lock->write); } static inline void rwlock_runlock(struct rwlock *lock) { __sync_sub_and_fetch(&lock->read,1); }
写个简单的程序跑下:
郑重声明:本站内容如果来自互联网及其他传播媒体,其版权均属原媒体及文章作者所有。转载目的在于传递更多信息及用于网络分享,并不代表本站赞同其观点和对其真实性负责,也不构成任何其他建议。