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
}

相关推荐

最近更新

  1. TCP协议是安全的吗?

    2024-04-07 05:34:03       18 阅读
  2. 阿里云服务器执行yum,一直下载docker-ce-stable失败

    2024-04-07 05:34:03       19 阅读
  3. 【Python教程】压缩PDF文件大小

    2024-04-07 05:34:03       18 阅读
  4. 通过文章id递归查询所有评论(xml)

    2024-04-07 05:34:03       20 阅读

热门阅读

  1. 【Rust】基础语法

    2024-04-07 05:34:03       22 阅读
  2. 设计模式:外观模式

    2024-04-07 05:34:03       17 阅读
  3. 机器学习软件perming的使用文档

    2024-04-07 05:34:03       15 阅读
  4. AJAX

    AJAX

    2024-04-07 05:34:03      14 阅读
  5. 设计模式:策略模式

    2024-04-07 05:34:03       37 阅读
  6. Spring和Spring Boot的区别

    2024-04-07 05:34:03       20 阅读
  7. Jenkins 入门

    2024-04-07 05:34:03       44 阅读
  8. 系统地自学Python的步骤与策略

    2024-04-07 05:34:03       46 阅读
  9. Python中主要数据结构的使用

    2024-04-07 05:34:03       18 阅读
  10. 网络安全介绍

    2024-04-07 05:34:03       20 阅读