借鉴于Go夜读,加了个人理解:https://reading.developerlearning.cn/articles/sync/sync_rwmutex_source_code_analysis/
go版本:go1.12 windows/amd64
sync/rwmutex.go是对 runtime/rwmutex.go文件的拷贝。
当一个协程获取到读锁,同时存在另一个协程调用写锁,这时不允许新的协程来获取读锁直到最新的读锁被释放;这能确保在递归循环读锁的情况下,写锁也能被调用,写锁阻止新的reader来获取lock.
也就是说,上写锁时要等之前的读锁释放,新的读操作会卡住,等待旧的读操作完,写锁运行完,卡住的读操作才会继续进行。
结构体
// If a goroutine holds a RWMutex for reading and another goroutine might
// call Lock, no goroutine should expect to be able to acquire a read lock
// until the initial read lock is released. In particular, this prohibits
// recursive read locking. This is to ensure that the lock eventually becomes
// available; a blocked Lock call excludes new readers from acquiring the
// lock.
type RWMutex struct {
w Mutex // 互斥锁
writerSem uint32 // 写锁信号量
readerSem uint32 // 读锁信号量
readerCount int32 // 还未释放读锁的reader数
readerWait int32 // 获取写锁时需要等待的读锁释放数量
}
常量
const rwmutexMaxReaders = 1 << 30 // 支持最多2^30个读锁
方法
以下是 sync.RWMutex 提供的4个方法
RLock
// RLock locks rw for reading.
//
// It should not be used for recursive read locking; a blocked Lock
// call excludes new readers from acquiring the lock
func (rw *RWMutex) RLock() { //读锁
if race.Enabled {
_ = rw.w.state
race.Disable()
}
// 每次 goroutine获取读锁时, readCount+1
// 如果写锁已经被获取,那么 readCount 在 -rwmutexMaxReaders 与 0 之间(当为0的时候,代表有2^30个读锁在等待,应该会出错,但是极端条件不会出现)
// 通过readCount 判断读锁与写锁 是否互斥,如果有写锁存在就挂起 goroutine,多个读锁可以并行
if atomic.AddInt32(&rw.readerCount, 1) < 0 {
// A writer is pending, wait for it.
runtime_Semacquire(&rw.readerSem) //等待reader信号量
}
if race.Enabled {
race.Enable()
race.Acquire(unsafe.Pointer(&rw.readerSem))
}
}
RUnlock
// RUnlock undoes a single RLock call;
// it does not affect other simultaneous readers.
// It is a run-time error if rw is not locked for reading
// on entry to RUnlock.
func (rw *RWMutex) RUnlock() { //释放读锁
if race.Enabled {
_ = rw.w.state
race.ReleaseMerge(unsafe.Pointer(&rw.writerSem))
race.Disable()
}
// 检查当前是否可以进行释放锁
if r := atomic.AddInt32(&rw.readerCount, -1); r < 0 {
// 1.r+1==0时,rw.readerCount -1= -1,rw.readerCount = 0则不存在读锁,表示直接执行RUnlock()
// 2.r+1=-rwmutexMaxReaders,rw.readerCount = -rwmutexMaxReaders ,
// 这种情况出现在获取Lock()方法,atomic.AddInt32(&rw.readerCount, -rwmutexMaxReaders),这时rw.readerCount = 0 也不存在读锁,表示执行Lock()再执行RUnlock()
if r+1 == 0 || r+1 == -rwmutexMaxReaders { //如果已经没有读锁的,还去释放(如释放多次)
race.Enable()
throw("sync: RUnlock of unlocked RWMutex")
}
// A writer is pending. 下面的情况代表有写锁
if atomic.AddInt32(&rw.readerWait, -1) == 0 { //写锁的reader wait数量-1
// The last reader unblocks the writer.
runtime_Semrelease(&rw.writerSem, false)//如果wait数量到0,释放writer信号量
}
}
if race.Enabled {
race.Enable()
}
}
Lock
// Lock locks rw for writing.
// If the lock is already locked for reading or writing,
// Lock blocks until the lock is available.
func (rw *RWMutex) Lock() { // 写锁加锁操作
if race.Enabled {
_ = rw.w.state
race.Disable()
}
// First, resolve competition with other writers.
rw.w.Lock() //上互斥锁
// Announce to readers there is a pending writer.
// 将当前的 readerCount 置为负数,告诉 RUnLock 当前存在写锁等待
r := atomic.AddInt32(&rw.readerCount, -rwmutexMaxReaders) + rwmutexMaxReaders
// Wait for active readers.
// 等待读锁释放
if r != 0 && atomic.AddInt32(&rw.readerWait, r) != 0 {//当前readCount不为0,并且上一步r计算之后RUnlock的次数和之前readerCount相同(上一步计算后可能有多次RUnlock,readerWait会变成负数)
runtime_Semacquire(&rw.writerSem)//等待writer信号量
}
if race.Enabled {
race.Enable()
race.Acquire(unsafe.Pointer(&rw.readerSem))
race.Acquire(unsafe.Pointer(&rw.writerSem))
}
}
Unlock
// Unlock unlocks rw for writing. It is a run-time error if rw is
// not locked for writing on entry to Unlock.
//
// As with Mutexes, a locked RWMutex is not associated with a particular
// goroutine. One goroutine may RLock (Lock) a RWMutex and then
// arrange for another goroutine to RUnlock (Unlock) it.
func (rw *RWMutex) Unlock() {
if race.Enabled {
_ = rw.w.state
race.Release(unsafe.Pointer(&rw.readerSem))
race.Release(unsafe.Pointer(&rw.writerSem))
race.Disable()
}
// 加上 Lock 的时候减去的 rwmutexMaxReaders
r := atomic.AddInt32(&rw.readerCount, rwmutexMaxReaders)
// 1.没执行Lock调用Unlock 2.释放写锁多次 抛出异常
if r >= rwmutexMaxReaders {
race.Enable()
throw("sync: Unlock of unlocked RWMutex")
}
// 通知当前等待的读锁
for i := 0; i < int(r); i++ {
runtime_Semrelease(&rw.readerSem, false)
}
// 释放 Mutex 锁
rw.w.Unlock()
if race.Enabled {
race.Enable()
}
}
RLocker
只对读操作加解锁
// RLocker returns a Locker interface that implements
// the Lock and Unlock methods by calling rw.RLock and rw.RUnlock.
func (rw *RWMutex) RLocker() Locker {
return (*rlocker)(rw)
}
type rlocker RWMutex
func (r *rlocker) Lock() { (*RWMutex)(r).RLock() }
func (r *rlocker) Unlock() { (*RWMutex)(r).RUnlock() }
思考
当调用写锁时,新的读锁会挂起,等待已经执行的读锁执行完,然后才执行写锁,锁的颗粒度应尽量小。