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);
}
原文:http://blog.csdn.net/vonzhoufz/article/details/38844165