PHP前端开发

Golang互斥锁内部实现的实例详解

百变鹏仔 2小时前 #Python
文章标签 详解

本篇文章主要介绍了详解golang互斥锁内部实现,小编觉得挺不错的,现在分享给大家,也给大家做个参考。一起跟随小编过来看看吧

go语言提供了一种开箱即用的共享资源的方式,互斥锁(sync.Mutex), sync.Mutex的零值表示一个没有被锁的,可以直接使用的,一个goroutine获得互斥锁后其他的goroutine只能等到这个gorutine释放该互斥锁,在Mutex结构中只公开了两个函数,分别是Lock和Unlock,在使用互斥锁的时候非常简单,本文并不阐述使用。

在使用sync.Mutex的时候千万不要做值拷贝,因为这样可能会导致锁失效。当我们打开我们的IDE时候跳到我们的sync.Mutex 代码中会发现它有如下的结构:


type Mutex struct { state int32   //互斥锁上锁状态枚举值如下所示 sema uint32  //信号量,向处于Gwaitting的G发送信号}const ( mutexLocked = 1 <p>上面的state值分别为 0(可用) 1(被锁) 2~31等待<a href="http://www.php.cn/code/9586.html" target="_blank">队列</a>计数</p><p>下面是互斥锁的源码,这里会有四个比较重要的方法需要提前解释,分别是runtime_canSpin,runtime_doSpin,runtime_SemacquireMutex,runtime_Semrelease,</p><p><span>立即学习</span>“<a href="https://pan.quark.cn/s/00968c3c2c15" style="text-decoration: underline !important; color: blue; font-weight: bolder;" rel="nofollow" target="_blank">go语言免费学习笔记(深入)</a>”;</p><p><strong>1、runtime_canSpin:</strong>比较保守的自旋,golang中自旋锁并不会一直自旋下去,在runtime包中runtime_canSpin方法做了一些限制, 传递过来的iter大等于4或者cpu核数小等于1,最大逻辑处理器大于1,至少有个本地的P队列,并且本地的P队列可运行G队列为空。</p><p class="jb51code"><br></p><pre class="brush:plain;">//go:linkname sync_runtime_canSpin sync.runtime_canSpinfunc sync_runtime_canSpin(i int) bool { if i &gt;= active_spin || ncpu <p><strong>2、 runtime_doSpin:</strong>会调用procyield函数,该函数也是汇编语言实现。函数内部<a href="http://www.php.cn/code/6276.html" target="_blank">循环</a>调用PAUSE指令。PAUSE指令什么都不做,但是会消耗CPU时间,在执行PAUSE指令时,CPU不会对它做不必要的优化。</p><p class="jb51code"><br></p><pre class="brush:plain;">//go:linkname sync_runtime_doSpin sync.runtime_doSpinfunc sync_runtime_doSpin() { procyield(active_spin_cnt)}

3、runtime_SemacquireMutex:


//go:linkname sync_runtime_SemacquireMutex sync.runtime_SemacquireMutexfunc sync_runtime_SemacquireMutex(addr *uint32) { semacquire(addr, semaBlockProfile|semaMutexProfile)}

4、runtime_Semrelease:


//go:linkname sync_runtime_Semrelease sync.runtime_Semreleasefunc sync_runtime_Semrelease(addr *uint32) { semrelease(addr)}Mutex的Lock函数定义如下func (m *Mutex) Lock() {    //先使用CAS尝试获取锁 if atomic.CompareAndSwapInt32(&amp;m.state, 0, mutexLocked) {        //这里是-race不需要管它 if race.Enabled {  race.Acquire(unsafe.Pointer(m)) }        //成功获取返回 return } awoke := false //循环标记 iter := 0    //循环计数器 for { old := m.state //获取当前锁状态 new := old | mutexLocked //将当前状态最后一位指定1 if old&amp;mutexLocked != 0 { //如果所以被占用  if runtime_canSpin(iter) { //检查是否可以进入自旋锁  if !awoke &amp;&amp; old&amp;mutexWoken == 0 &amp;&amp; old&gt;&gt;mutexWaiterShift != 0 &amp;&amp;   atomic.CompareAndSwapInt32(&amp;m.state, old, old|mutexWoken) {                     //awoke标记为true   awoke = true  }                //进入自旋状态  runtime_doSpin()  iter++  continue  }            //没有获取到锁,当前G进入Gwaitting状态  new = old + 1&gt;mutexWaiterShift == 0 || old&amp;(mutexLocked|mutexWoken) != 0 {  return } // 减少等待次数,添加清除标记 new = (old - 1<p>互斥锁无冲突是最简单的情况了,有冲突时,首先进行自旋,,因为大多数的Mutex保护的代码段都很短,经过短暂的自旋就可以获得;如果自旋等待无果,就只好通过信号量来让当前Goroutine进入Gwaitting状态。</p>