RWMutex
结构体
type RWMutex struct {
w Mutex // held if there are pending writers
writerSem uint32 // semaphore for writers to wait for completing readers
readerSem uint32 // semaphore for readers to wait for completing writers
readerCount atomic.Int32 // number of pending readers
readerWait atomic.Int32 // number of departing readers
}
原理
- 读写锁写时阻塞读,读时阻塞写,允许多个同时读
读加锁
- readcount 加1,判断readcount < 0,说明存在写锁,在readerSem阻塞等待
读解锁
- readcount 减1,readwait 减1,如果readwait == 0,说明没有等待的读协程,释放writerSem,激活写协程
写加锁
- readcount 减一个大数,如果当前readcount >0,说明存在读锁,在writerSem阻塞等待,并将当当前的读协程数量赋值给 readwait。
写解锁
- readcount 加回来一个大数,如果readcount > 0, 说明还有读协程在等待,唤醒readerSem