go sync包(二) 互斥锁(二)

互斥锁 Mutex

mutex 的 加解锁很简单:

	var mutex sync.Mutex
	mutex.Lock()
	defer mutex.Unlock()
	// 加锁期间的代码逻辑

加锁

// Lock locks m.
// If the lock is already in use, the calling goroutine
// blocks until the mutex is available.
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()
}
  • 当我们调用 Lock 方法的时候,会先尝试走 Fast Path,也就是如果当前互斥锁如果处于未加锁的状态,尝试加锁,只要加锁成功就直接返回。
  • 否则的话就进入 slow path。
func (m *Mutex) lockSlow() {
   var waitStartTime int64 // 等待时间
   starving := false // 是否处于饥饿状态
   awoke := false // 是否处于唤醒状态
   iter := 0 // 自旋迭代次数
   old := m.state 
   for {
      // Don't spin in starvation mode, ownership is handed off to waiters
      // so we won't be able to acquire the mutex anyway.
      
      // 判断当前 Goroutine 能否进入自旋
      // 条件:
      // 当前处于普通模式 && runtime_canSpin 返回 true
      // runtime_canSpin 返回 true
      //     1. 运行在多 CPU 的机器上
      //     2. 自旋次数不超过 4 次
      //     3. 当前机器上至少存在一个正在运行的处理器 P 并且处理的运行队列为空
      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.
         // 尝试设置 mutexWoken 状态,避免唤醒其他休眠的 goroutine
         if !awoke && old&mutexWoken == 0 && old>>mutexWaiterShift != 0 &&
            atomic.CompareAndSwapInt32(&m.state, old, old|mutexWoken) {
            awoke = true
         }
         // 自旋:执行 30 次 PAUSE指令,占用CPU并消耗CPU时间
         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.
         if new&mutexWoken == 0 {
            throw("sync: inconsistent mutex state")
         }
         new &^= mutexWoken
      }
      
      // CAS更新状态获取锁
      // 正常模式:这段代码会设置唤醒和饥饿标记、重置迭代次数并重新执行获取锁的循环。
      // 饥饿模式: 当前 Goroutine 会获得互斥锁,如果等待队列中只存在当前 Goroutine,
      // 互斥锁还会从饥饿模式中退出。
      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()
         }
         // 阻塞
         runtime_SemacquireMutex(&m.sema, queueLifo, 1)
         // 看是否超过 1ms,是的话就切换到公平模式
         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")
            }
            // 退出饥饿模式
            delta := int32(mutexLocked - 1<<mutexWaiterShift)
            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 {
         old = m.state
      }
   }

   if race.Enabled {
      race.Acquire(unsafe.Pointer(m))
   }
}
  1. 判断当前 goroutine 能否可以进入自旋状态,可以的话自旋争抢锁。
    进入自旋状态的条件:
    • 普通模式
    • 运行在多 CPU 的机器上
    • 自旋次数不超过 4 次
    • 当前机器上至少存在一个正在运行的处理器 P 并且处理的运行队列为空
  2. 普通模式:被唤醒的 goroutine 跟新到来的 goroutine 争抢锁。
    饥饿模式:新到来的 goroutine 自动加入队列末尾,由队列第一个 goroutine 获得锁。
  3. 饥饿模式:
    进入条件:如果当前 goroutine 超过 1ms 都没有获取到锁就会进饥饿模式。
    退出条件:当前 goroutine 是队列中最后一个 goroutine。

解锁

// Unlock unlocks m.
// It is a run-time error if m is not locked on entry to Unlock.
//
// A locked Mutex is not associated with a particular goroutine.
// It is allowed for one goroutine to lock a Mutex and then
// arrange for another goroutine to unlock it.
func (m *Mutex) Unlock() {
   if race.Enabled {
      _ = m.state
      race.Release(unsafe.Pointer(m))
   }

   // Fast path: drop lock bit.
   new := atomic.AddInt32(&m.state, -mutexLocked)
   if new != 0 {
      // Outlined slow path to allow inlining the fast path.
      // To hide unlockSlow during tracing we skip one extra frame when tracing GoUnblock.
      m.unlockSlow(new)
   }
}
  • 如果该函数返回的新状态等于 0,当前 Goroutine 就成功解锁了互斥锁。
  • 如果该函数返回的新状态不等于 0,这段代码会调用 sync.Mutex.unlockSlow 开始慢速解锁。
func (m *Mutex) unlockSlow(new int32) {
   // 校验锁状态的合法性
   // 如果当前互斥锁已经被解锁过,直接抛出异常中止当前程序
   if (new+mutexLocked)&mutexLocked == 0 {
      fatal("sync: unlock of unlocked mutex")
   }
   // 普通模式
   if new&mutexStarving == 0 {
      old := new
      for {
         // If there are no waiters or a goroutine has already
         // been woken or grabbed the lock, no need to wake anyone.
         // In starvation mode ownership is directly handed off from unlocking
         // goroutine to the next waiter. We are not part of this chain,
         // since we did not observe mutexStarving when we unlocked the mutex above.
         // So get off the way.
         // 
         // 没有等待者 || 已经被加锁 || 已经被解锁 || 公平锁
         if old>>mutexWaiterShift == 0 || old&(mutexLocked|mutexWoken|mutexStarving) != 0 {
            return
         }
         // Grab the right to wake someone.
         // 唤醒一个等待者
         new = (old - 1<<mutexWaiterShift) | mutexWoken
         if atomic.CompareAndSwapInt32(&m.state, old, new) {
            runtime_Semrelease(&m.sema, false, 1)
            return
         }
         old = m.state
      }
   } else {
      // Starving mode: handoff mutex ownership to the next waiter, and yield
      // our time slice so that the next waiter can start to run immediately.
      // Note: mutexLocked is not set, the waiter will set it after wakeup.
      // But mutex is still considered locked if mutexStarving is set,
      // so new coming goroutines won't acquire it.
      // 饥饿模式
      // 将当前锁让给下一个等待者
      // 这里不会解除饥饿模式,所以新来的goroutine不会获得锁
      runtime_Semrelease(&m.sema, true, 1)
   }
}


// Semrelease atomically increments *s and notifies a waiting goroutine
// if one is blocked in Semacquire.
// It is intended as a simple wakeup primitive for use by the synchronization
// library and should not be used directly.
// If handoff is true, pass count directly to the first waiter.
// skipframes is the number of frames to omit during tracing, counting from
// runtime_Semrelease's caller.

// hadoff:
// true: 唤醒并直接移交给第一个等待者
// false: 只是唤醒操作
func runtime_Semrelease(s *uint32, handoff bool, skipframes int)

小结

互斥锁的加锁过程比较复杂,它涉及自旋、信号量以及调度等概念:

  • 如果互斥锁处于初始化状态,会通过置位 mutexLocked 加锁。
  • 如果互斥锁处于 mutexLocked 状态并且在普通模式下工作,会进入自旋,执行 30 次 PAUSE 指令消耗 CPU 时间等待锁的释放。
  • 如果当前 Goroutine 等待锁的时间超过了 1ms,互斥锁就会切换到饥饿模式。
  • 互斥锁在正常情况下会通过 runtime.sync_runtime_SemacquireMutex 将尝试获取锁的 Goroutine 切换至休眠状态,等待锁的持有者唤醒(阻塞)。
  • 如果当前 Goroutine 是互斥锁上的最后一个等待的协程,那么它会将互斥锁切换回正常模式。

互斥锁的解锁过程比较简单:

  • 当互斥锁已经被解锁时,调用 sync.Mutex.Unlock 会直接抛出异常。
  • 当互斥锁处于饥饿模式时,将锁的所有权交给队列中的下一个等待者,等待者会负责设置 mutexLocked 标志位。
  • 当互斥锁处于普通模式时,如果没有 Goroutine 等待锁的释放或者已经有被唤醒的 Goroutine 获得了锁,会直接返回。在其他情况下会通过 sync.runtime_Semrelease 唤醒对应的 Goroutine。
  • 5
    点赞
  • 7
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值