const ( mutexLocked = 1 << iota// mutex is locked state & mutexLocked 1==加锁 0==未加锁
mutexWoken //state & mutexWoken 1==唤醒 0==未唤醒 mutexStarving // state & mutexStarving 1==饥饿状态 0==正常状态 mutexWaiterShift = iota// state >> mutexWaiterShift得到当前的goroutine数量
// Mutex fairness. // 两种模式:正常或饥饿 // Mutex can be in 2 modes of operations: normal and starvation. // 正常模式就是FIFO队列。 // In normal mode waiters are queued in FIFO order, but a woken up waiter // does not own the mutex and competes with new arriving goroutines over // the ownership. New arriving goroutines have an advantage -- they are // already running on CPU and there can be lots of them, so a woken up // waiter has good chances of losing. In such case it is queued at front // of the wait queue. If a waiter fails to acquire the mutex for more than 1ms, //获取锁的时间超过1ms,切换到饥饿模式 // it switches mutex to the starvation mode. // // In starvation mode ownership of the mutex is directly handed off from //饥饿模式下锁的所有权直接从解锁goroutine的waiter手中移交到队列的前面。 // the unlocking goroutine to the waiter at the front of the queue. // New arriving goroutines don't try to acquire the mutex even if it appears // to be unlocked, and don't try to spin. Instead they queue themselves at // the tail of the wait queue. // // If a waiter receives ownership of the mutex and sees that either //如果一个锁的所有权的等待者是以下两种情况之一的:1、处于队列的最后一个2、等待时间少于1ms,则切换到正常模式 // (1) it is the last waiter in the queue, or (2) it waited for less than 1 ms, // it switches mutex back to normal operation mode. // // Normal mode has considerably better performance as a goroutine can acquire // a mutex several times in a row even if there are blocked waiters. // Starvation mode is important to prevent pathological cases of tail latency. starvationThresholdNs = 1e6 )
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() }
func(m *Mutex) lockSlow() { var waitStartTime int64//等待时间 starving := false//是否处于饥饿状态 awoke := false//唤醒状态 iter := 0//自旋次数 old := m.state //当前状态copy for { // Don't spin in starvation mode, ownership is handed off to waiters // so we won't be able to acquire the mutex anyway. //加锁且能够自旋 if old&(mutexLocked|mutexStarving) == mutexLocked && runtime_canSpin(iter) { // Active spinning makes sense. // Try to set mutexWoken flag to inform Unlock // to not wake other blocked goroutines. //自旋过程发现没有被置woken标识,设置标识,将自己置为唤醒 if !awoke && old&mutexWoken == 0 && old>>mutexWaiterShift != 0 && atomic.CompareAndSwapInt32(&m.state, old, old|mutexWoken) { awoke = true } runtime_doSpin() //自旋 iter++ old = m.state //状态重置 continue } //更新状态 new := old // Don't try to acquire starving mutex, new arriving goroutines must queue. //非饥饿模式,则置锁 if old&mutexStarving == 0 { new |= mutexLocked } // 处于饥饿模式下,新来的goroutine进入队列中 if old&(mutexLocked|mutexStarving) != 0 { new += 1 << mutexWaiterShift } // The current goroutine switches mutex to starvation mode. // But if the mutex is currently unlocked, don't do the switch. // Unlock expects that starving mutex has waiters, which will not // be true in this case. //切换到饥饿模式下 if starving && old&mutexLocked != 0 { new |= mutexStarving } //当前处于唤醒状态,则重置清除唤醒状态。 if awoke { // The goroutine has been woken from sleep, // so we need to reset the flag in either case. ifnew&mutexWoken == 0 { throw("sync: inconsistent mutex state") } new &^= mutexWoken } //CAS更新状态。 if atomic.CompareAndSwapInt32(&m.state, old, new) { //获取到锁 if old&(mutexLocked|mutexStarving) == 0 { break// locked the mutex with CAS } // If we were already waiting before, queue at the front of the queue. //等待队列的时间 queueLifo := waitStartTime != 0 if waitStartTime == 0 { waitStartTime = runtime_nanotime() } //acquire阻塞队列.... // 新来的 goroutine, queueLifo=false, 加入到等待队列的尾部,耐心等待 // 唤醒的 goroutine, queueLifo=true, 加入到等待队列的头部 runtime_SemacquireMutex(&m.sema, queueLifo, 1) starving = starving || runtime_nanotime()-waitStartTime > starvationThresholdNs old = m.state //处于饥饿模式 if old&mutexStarving != 0 { // If this goroutine was woken and mutex is in starvation mode, // ownership was handed off to us but mutex is in somewhat // inconsistent state: mutexLocked is not set and we are still // accounted as waiter. Fix that. if old&(mutexLocked|mutexWoken) != 0 || old>>mutexWaiterShift == 0 { throw("sync: inconsistent mutex state") } //等待的goroutine-1 delta := int32(mutexLocked - 1<<mutexWaiterShift) // 处于队列中最后一个或者请求锁的时间未超过starvationThresholdNs,则回退到正常模式。 if !starving || old>>mutexWaiterShift == 1 { // Exit starvation mode. // Critical to do it here and consider wait time. // Starvation mode is so inefficient, that two goroutines // can go lock-step infinitely once they switch mutex // to starvation mode. delta -= mutexStarving } //更新状态 atomic.AddInt32(&m.state, delta) break } //重置迭代器和唤醒表示,继续获取锁 awoke = true iter = 0 } else { //CAS失败,则更新状态,继续获取。 old = m.state } }
if race.Enabled { race.Acquire(unsafe.Pointer(m)) } }