golang-互斥锁-mutex-源码阅读笔记

互斥锁的机制

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
评论
成就一亿技术人!
拼手气红包6.0元
还能输入1000个字符
 
红包 添加红包
表情包 插入表情
 条评论被折叠 查看
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值