read_lock()和write_lock()的过程描述如下:
锁变量的初值为RW_LOCK_UNLOCKED(0x01000000),锁变量为正时为未锁状态,反之为上锁状态。(说白了锁就是有一个数,初始值为0x01000000)
read_lock()对锁变量减1,如果结果为负,则说明已被某个write_lock()上锁。然后read_lock()对锁变量加1,释 放read_lock状态,接着等待锁变量的值变为1;一旦锁变量变为1,read_lock()再次对锁变量减1 ,如果非负则成功,否则重复上述过程。
write_lock()对锁变量减0x01000000,如果结果非零,则说明已被write_lock()或read_lock()上锁。然 后write_lock()对锁变量加0x01000000,释放write_lock()状态,接着等待锁变量的值变为0x01000000;一旦锁变 量变为0x01000000,write_lock()再次对锁变量减0x01000000,如果为零则成功,否则重复上述过程。
read_lock(&mr_rwlock);
write_lock(&mr_rwlock);
deadlocks as the write lock spins, waiting for all readers to release the lockincluding yourself. If you ever need to write, obtain the write lock from the very start. If the line between your readers and writers is muddled, it might be an indication that you do not need to use reader-writer locks. In that case, a normal spin lock is optimal.
执行上面2行代码的进程将阻塞到write_lock(&mr_rwlock); 因为mr_rwlock读锁没有释放
可以多个同时读,但是读-写, , 写-写 都是 互斥的
原理和 spin_lock一样
阅读(4638) | 评论(0) | 转发(0) |