互斥锁的机制
Go语言中互斥锁(Mutex)的公平性机制。互斥锁是一种用于保护共享资源,防止多个goroutine同时访问的同步原语。这段注释详细说明了互斥锁的两种操作模式:普通模式和饥饿模式。
普通模式(Normal Mode)
在普通模式下,等待获取锁的goroutine会按照先进先出(FIFO)的顺序排队。当一个等待的goroutine被唤醒时,它并不直接拥有锁,而是与新到达的goroutine竞争锁的所有权。新到达的goroutine由于已经在运行,因此在竞争中有优势。如果一个等待的goroutine在竞争中失败,它会被重新排队到等待队列的前面。如果一个goroutine连续1毫秒以上无法获取锁,互斥锁会切换到饥饿模式。
饥饿模式(Starvation Mode)
在饥饿模式下,锁的所有权直接从解锁的goroutine传递给等待队列前面的goroutine。新到达的goroutine即使发现锁处于未锁定状态,也不会尝试获取锁,而是直接排队到等待队列的末尾。这种模式下,新到达的goroutine不会尝试自旋(即不断尝试获取锁)。
模式切换
如果一个goroutine成功获取到锁,并且发现它是队列中的最后一个等待者,或者它等待的时间少于1毫秒,它会将互斥锁切换回普通模式。
性能考虑
普通模式具有更好的性能,因为一个goroutine可以连续多次获取锁,即使有阻塞的等待者。饥饿模式则用于防止极端情况下的尾部延迟问题,确保等待时间较长的goroutine能够及时获取锁。
介绍
数据结构
// A Mutex is a mutual exclusion lock.
type Mutex struct {
state int32
sema uint32
}

包中的常量
const (
// mutex = 1
mutexLocked = 1 << iota // mutex is locked
// mutexWoken = 2
mutexWoken
// mutexStarving = 4
mutexStarving
// mutexWaiterShift = 3
mutexWaiterShift = iota
// Mutex fairness.
//
// Mutex can be in 2 modes of operations: normal and starvation.
// 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,
// it switches mutex to the starvation mode.
//
// In starvation mode ownership of the mutex is directly handed off from
// 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) 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 pathol

最低0.47元/天 解锁文章
858

被折叠的 条评论
为什么被折叠?



