1.sync.Mutex互斥锁底层实现
2.sync.RwMutex读写锁底层实现
1.sync.Mutex互斥锁底层实现
通过cas原子操作加锁,通过信号量实现协程唤醒
锁有两种模式,正常模式和饥饿模式
正常模式(非公平锁):所有阻塞在等待队列的go协程会按顺序获取锁,通常新请求的go协程会更容易获取锁
饥饿模式(公平锁):新请求锁的go协程不会获取锁,而是加入队列尾部阻塞等待
饥饿模式触发条件:当一个go协程等待锁的时间超过1ms
2.sync.RwMutex读写锁底层实现
支持并发读,读锁不阻塞读,阻塞写; 写锁 会阻塞读和写
适合读多写少
type Mutex struct {
state int32 // cas加锁
sema uint32 // 信号量,实现协程阻塞和唤醒
}
const (
mutexLocked = 1 << iota // mutex is locked
mutexWoken
mutexStarving
mutexWaiterShift = iota
)
func (m *Mutex) Lock() {
// Fast path: grab unlocked mutex.
if atomic.CompareAndSwapInt32(&m.state, 0, mutexLocked) {
if race.Enabled {
race.Acquire(unsafe.Pointer(m))
}
return
}
// Slow path (outlined so that the fast path can be inlined)
m.lockSlow()
}
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 int32 // number of pending readers
readerWait int32 // number of departing readers
}