本篇文章主要介绍了详解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 << iota // 1 互斥锁是锁定的 mutexWoken // 2 唤醒锁 mutexWaiterShift = iota // 2 统计阻塞在这个互斥锁上的goroutine数目需要移位的数值 )
上面的state值分别为 0(可用) 1(被锁) 2~31等待队列计数
下面是互斥锁的源码,这里会有四个比较重要的方法需要提前解释,分别是runtime_canSpin,runtime_doSpin,runtime_SemacquireMutex,runtime_Semrelease,
1、runtime_canSpin:比较保守的自旋,golang中自旋锁并不会一直自旋下去,在runtime包中runtime_canSpin方法做了一些限制, 传递过来的iter大等于4或者cpu核数小等于1,最大逻辑处理器大于1,至少有个本地的P队列,并且本地的P队列可运行G队列为空。
//go:linkname sync_runtime_canSpin sync.runtime_canSpin func sync_runtime_canSpin(i int) bool { if i >= active_spin || ncpu <= 1 || gomaxprocs <= int32(sched.npidle+sched.nmspinning)+1 { return false } if p := getg().m.p.ptr(); !runqempty(p) { return false } return true }
2、 runtime_doSpin:会调用procyield函数,该函数也是汇编语言实现。函数内部循环调用PAUSE指令。PAUSE指令什么都不做,但是会消耗CPU时间,在执行PAUSE指令时,CPU不会对它做不必要的优化。
//go:linkname sync_runtime_doSpin sync.runtime_doSpin func sync_runtime_doSpin() { procyield(active_spin_cnt) }
3、runtime_SemacquireMutex:
//go:linkname sync_runtime_SemacquireMutex sync.runtime_SemacquireMutex func sync_runtime_SemacquireMutex(addr *uint32) { semacquire(addr, semaBlockProfile|semaMutexProfile) }
4、runtime_Semrelease:
//go:linkname sync_runtime_Semrelease sync.runtime_Semrelease func sync_runtime_Semrelease(addr *uint32) { semrelease(addr) } Mutex的Lock函数定义如下 func (m *Mutex) Lock() { //先使用CAS尝试获取锁 if atomic.CompareAndSwapInt32(&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&mutexLocked != 0 { //如果所以被占用 if runtime_canSpin(iter) { //检查是否可以进入自旋锁 if !awoke && old&mutexWoken == 0 && old>>mutexWaiterShift != 0 && atomic.CompareAndSwapInt32(&m.state, old, old|mutexWoken) { //awoke标记为true awoke = true } //进入自旋状态 runtime_doSpin() iter++ continue } //没有获取到锁,当前G进入Gwaitting状态 new = old + 1<<mutexWaiterShift } if awoke { if new&mutexWoken == 0 { throw("sync: inconsistent mutex state") } //清除标记 new &^= mutexWoken } //更新状态 if atomic.CompareAndSwapInt32(&m.state, old, new) { if old&mutexLocked == 0 { break } // 锁请求失败,进入休眠状态,等待信号唤醒后重新开始循环 runtime_SemacquireMutex(&m.sema) awoke = true iter = 0 } } if race.Enabled { race.Acquire(unsafe.Pointer(m)) } } Mutex的Unlock函数定义如下 func (m *Mutex) Unlock() { if race.Enabled { _ = m.state race.Release(unsafe.Pointer(m)) } // 移除标记 new := atomic.AddInt32(&m.state, -mutexLocked) if (new+mutexLocked)&mutexLocked == 0 { throw("sync: unlock of unlocked mutex") } old := new for { //当休眠队列内的等待计数为0或者自旋状态计数器为0,退出 if old>>mutexWaiterShift == 0 || old&(mutexLocked|mutexWoken) != 0 { return } // 减少等待次数,添加清除标记 new = (old - 1<<mutexWaiterShift) | mutexWoken if atomic.CompareAndSwapInt32(&m.state, old, new) { // 释放锁,发送释放信号 runtime_Semrelease(&m.sema) return } old = m.state } }
互斥锁无冲突是最简单的情况了,有冲突时,首先进行自旋,,因为大多数的Mutex保护的代码段都很短,经过短暂的自旋就可以获得;如果自旋等待无果,就只好通过信号量来让当前Goroutine进入Gwaitting状态。
Atas ialah kandungan terperinci Golang互斥锁内部实现的实例详解. Untuk maklumat lanjut, sila ikut artikel berkaitan lain di laman web China PHP!

Pythonusesahybridapproach, combiningcompilationtobytecodeandinterpretation.1) codeiscompiledtopplatform-independentbytecode.2) byteCodeisinterpretedbythepythonvirtualmachine, enhancingficiencyAndortability.

TheKeydifferencesbetweenpython's "for" and "while" loopsare: 1) "untuk" loopsareidealforiteratingoversequencesorknowniterations, while2) "manakala" loopsarebetterforcontinuinguntilaconditionismetwithoutpredefinediterations.un

Di Python, anda boleh menyambungkan senarai dan menguruskan elemen pendua melalui pelbagai kaedah: 1) Gunakan pengendali atau melanjutkan () untuk mengekalkan semua elemen pendua; 2) Tukar ke set dan kemudian kembali ke senarai untuk mengalih keluar semua elemen pendua, tetapi pesanan asal akan hilang; 3) Gunakan gelung atau senarai pemantauan untuk menggabungkan set untuk menghapuskan elemen pendua dan mengekalkan urutan asal.

ThfastestmethodforlistconcatenationInpythondondedonListsize: 1) forsmalllists, the operatoriseSefficient.2) forlargerlists, list.extend () orlistComprehensionisfaster, withExtend () ausmorememory-efficientyModifingListsin-tempat.

ToinSertelementsIntoapythonlist, useAppend () toaddtotheend, memasukkan () foraspecificposition, andExtend () formultipleelements.1) useAppend () foraddingsingleitemstotheend.2) useInsert () toaddataSpecificIndex, evenItForForForForForForShoStoRd

Pythonlistsareimplementedasdynamicarrays, notlinkedlists.1) thearestoredincontiguousmemoryblocks, yangMayrequireReAllocationWhenAppendingItems, ImpactingPormance.2) LinkedListSwouldOfferefficientInsertions/DeletionsButsCoweCcess

PythonoffersfourmainmethodstoremoveelementsFromalist: 1) Keluarkan (nilai) RemoveStHefirStoccurrenceFavalue, 2) Pop (index) RemoveRandReturnSanelementAtaspeciedIndex, 3)

Ralat toresolvea "kebenaran" yang mana -mana, berikut: 1) checkandadjustthescript'spermissionsingchmod xmyscript.shtomakeitexecutable.2) EnsurethescriptislocatedInadirectoryHeryouhaveVerPiSs, suchasyoursory, suchasyourshy, suchasyourperhysh, suchasyourshy.


Alat AI Hot

Undresser.AI Undress
Apl berkuasa AI untuk mencipta foto bogel yang realistik

AI Clothes Remover
Alat AI dalam talian untuk mengeluarkan pakaian daripada foto.

Undress AI Tool
Gambar buka pakaian secara percuma

Clothoff.io
Penyingkiran pakaian AI

Video Face Swap
Tukar muka dalam mana-mana video dengan mudah menggunakan alat tukar muka AI percuma kami!

Artikel Panas

Alat panas

SublimeText3 versi Cina
Versi Cina, sangat mudah digunakan

Hantar Studio 13.0.1
Persekitaran pembangunan bersepadu PHP yang berkuasa

PhpStorm versi Mac
Alat pembangunan bersepadu PHP profesional terkini (2018.2.1).

EditPlus versi Cina retak
Saiz kecil, penyerlahan sintaks, tidak menyokong fungsi gesaan kod

Notepad++7.3.1
Editor kod yang mudah digunakan dan percuma
