golang mutex

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
}

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值