代码改变世界

Golang Mutex锁分析

2021-06-30 10:48  宋海宾  阅读(101)  评论(0编辑  收藏  举报

1.功能

 并发场景的互斥和同步

 

2.使用

import  sync

var  mutex   sync.Mutex

 

func fn(){

  mutex.Lock()

  defer mutex.Unlock()

  fmt.Print("mutex ...")

}

3.原理

type Mutex struct {
  state int32
  sema uint32
}
 
func (m *Mutex) Lock() {
  //快速获取锁  mutexLocked = 1 << iota
  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()
}
 
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)
  }
}