您的位置 首页 golang

Go语言中互斥锁与读写锁,你知多少?

简述

Golang中的锁机制主要包含互斥锁和 读写锁

互斥锁

互斥锁是传统并发程序对共享资源进行控制访问的主要手段。在Go中主要使用 sync.Mutex的结构体表示。

一个简单的示例:

func mutex() {
 var mu sync.Mutex
 mu.Lock()
 fmt.Println("locked")
 mu.Unlock()
} 

或者也可以使用defer来实现,这在整个函数流程中全部要加锁时特别有用,还有一个好处就是可以防止忘记Unlock

func mutex() {
 var mu sync.Mutex
 mu.Lock()
 defer mu.Unlock()
 fmt.Println("locked")
} 

互斥锁是开箱即用的,只需要申明sync.Mutex即可直接使用

var mu sync.Mutex 

互斥锁应该是成对出现,在同步语句不可以再对锁加锁,看下面的示例:

func mutex() {
 var mu sync.Mutex
 mu.Lock()
 fmt.Println("parent locked")
 mu.Lock()
 fmt.Println("sub locked")
 mu.Unlock()
 mu.Unlock()
} 

此时则会出现fatal error: all goroutines are asleep – deadlock!错误

同样,如果多次对一个锁解锁,则会出现fatal error: sync: unlock of unlocked mutex错误

func mutex() {
 var mu sync.Mutex
 mu.Lock()
 fmt.Println("locked")
 mu.Unlock()
 mu.Unlock()
} 

那么在goroutine中是否对外部锁加锁呢?

func mutex() {
 var mu sync.Mutex
 fmt.Println("parent lock start")
 mu.Lock()
 fmt.Println("parent locked")
 for i := 0; i <= 2; i++ {
 go func(i int) {
 fmt. Printf ("sub(%d) lock startn", i)
 mu.Lock()
 fmt.Printf("sub(%d) lockedn", i)
 time.Sleep(time.Microsecond * 30)
 mu.Unlock()
 fmt.Printf("sub(%d) unlockn", i)
 }(i)
 }
 time.Sleep(time.Second * 2)
 mu.Unlock()
 fmt.Println("parent unlock")
 time.Sleep(time.Second * 2)
} 

先看上面的函数执行结果

parent lock start
parent locked
sub(0) lock start
sub(2) lock start
sub(1) lock start
parent unlock // 必须等到父级先解锁,后面则会阻塞
sub(0) locked // 解锁后子goroutine才能执行锁定
sub(0) unlock
sub(2) locked
sub(2) unlock
sub(1) locked
sub(1) unlock 

为了方便调试,使用了time.Sleep()来延迟保证goroutine的执行 从结果中可以看出,当所有的goroutine遇到Lock时都会阻塞,而当main函数中的Unlock执行后,会有一个优先(无序)的goroutine来占得锁,其它的则再次进入阻塞状态。

总结:

  • 互斥锁必须成对出现
  • 同级别互斥锁不能嵌套使用
  • 父级中如果存在锁,当在goroutine中执行重复锁定操作时goroutine将被阻塞,直到原互斥锁解锁,多个goroutine将会争抢当前锁资源,其它继续阻塞。

Go语言中互斥锁与读写锁,你知多少?

读写锁

读写锁和互斥锁不同之处在于,可以分别针对读操作和写操作进行分别锁定,这样对于性能有一定的提升。 读写锁,对于多个写操作,以及写操作和读操作之前都是互斥的这一点基本等同于互斥锁。 但是对于同时多个读操作之前却非互斥关系,这也是相读写锁性能高于互斥锁的主要原因。

读写锁也是开箱即用型的

var rwm = sync.RWMutex 

读写锁分为写锁和读锁:

  • 写锁定和写解锁
rwm.Lock()
rwm.Unlock() 
  • 读锁定和读解锁
rwm.RLock()
rwm.RUnlock() 

读写锁的读锁和写锁不能交叉相互解锁,否则会发生panic,如:

func rwMutex() {
 var rwm sync.RWMutex

 rwm.Lock()
 fmt.Println("locked")
 rwm.RUnlock()
} 

fatal error: sync: RUnlock of unlocked RWMutex

对于读写锁,同一资源可以同时有多个读锁定,如:

func rwMutex() {
 var rwm sync.RWMutex

 rwm.RLock()
 rwm.RLock()
 rwm.RLock()
 fmt.Println("locked")
 rwm.RUnlock()
 rwm.RUnlock()
 rwm.RUnlock()
} 

但对于写锁定只能有一个(和互斥锁相同),同时使用多个会产生deadlock的panic,如:

func rwMutex() {
 var rwm sync.RWMutex

 rwm.Lock()
 rwm.Lock()
 rwm.Lock()
 fmt.Println("locked")
 rwm.Unlock()
 rwm.Unlock()
 rwm.Unlock()
} 

在goroutine中,写解锁会试图唤醒所有想要进行读锁定而被阻塞的goroutine。

而读解锁会在已无任何读锁定的情况下,试图唤醒一个想进行写锁定而被阻塞的goroutine。

下面看一个完整示例:

func rwMutex() {
 var rwm sync.RWMutex

 for i := 0; i <= 2; i++ {
 go func(i int) {
 fmt.Printf("go(%d) start lockn", i)
 rwm.RLock()
 fmt.Printf("go(%d) lockedn", i)
 time.Sleep(time.Second * 2)
 rwm.RUnlock()
 fmt.Printf("go(%d) unlockn", i)
 }(i)
 }
 // 先sleep一小会,保证for的goroutine都会执行
 time.Sleep(time.Microsecond * 100)
 fmt.Println("main start lock")
 // 当子进程都执行时,且子进程所有的资源都已经Unlock了
 // 父进程才会执行
 rwm.Lock()
 fmt.Println("main locked")
 time.Sleep(time.Second)
 rwm.Unlock()
} 
go(0) start lock
go(0) locked
go(1) start lock
go(1) locked
go(2) start lock
go(2) locked
main start lock
go(2) unlock
go(0) unlock
go(1) unlock
main locked 

反复执行上述示例中,可以看到,写锁定会阻塞goroutine 最开始先在main中sleep 100ms ,保证子的goroutine会全部执行,而每个子goroutine会sleep 2s。 此时会阻塞整个main进程,当所有子goroutine执行结束,读解锁后,main的写锁定才会执行。

再看一个读锁定示例:

func rwMutex5() {
 var rwm sync.RWMutex

 for i := 0; i <= 2; i++ {
 go func(i int) {
 fmt.Printf("go(%d) start lockn", i)
 rwm.RLock()
 fmt.Printf("go(%d) lockedn", i)
 time.Sleep(time.Second * 2)
 rwm.RUnlock()
 fmt.Printf("go(%d) unlockn", i)
 }(i)
 }

 fmt.Println("main start lock")
 rwm.RLock()
 fmt.Println("main locked")
 time.Sleep(time.Second * 10)
} 
main start lock
main locked
go(1) start lock
go(1) locked
go(2) start lock
go(2) locked
go(0) start lock
go(0) locked
go(0) unlock
go(1) unlock
go(2) unlock 

可以看到读锁定却并不会阻塞goroutine。

总结:

  • 读锁定和写锁定对于写操作都是互斥的
  • 读锁定支持多级嵌套,但写锁定无法嵌套执行
  • 如果有写锁定,当多个读解锁全部执行完成后,则会唤起执行写锁定
  • 写锁定会阻塞goroutine(在Lock()时和互斥锁一样,RLock()时先也是等到RUnlock()先执行,才有锁定机会)

感谢阅读

文章来源:智云一二三科技

文章标题:Go语言中互斥锁与读写锁,你知多少?

文章地址:https://www.zhihuclub.com/98862.shtml

关于作者: 智云科技

热门文章

评论已关闭

35条评论

  1. Like most service industries, also the translation industry is sometimes amazingly difficult to approach

  2. Resolute and resolute, the military orders Where To Buy Viagra Pill x1 male enhancement contact info are still like mountains, and the soldiers still have a Penis Stretching cialis pills for sale lot of expectations for the outside world, even if they know that they will experience a war, few people refuse The clinical evidence published to date indicates that dapoxetine 30 mg or 60 mg is an efficacious and tolerable treatment for lifelong and acquired PE, leading to significant improvement not only in the main disease symptom of IELT, but also in all patient-reported outcomes

  3. The only thing I d id note was slight shortness of breath, but it s important to note that I do have an arrhythmia, so although it felt a little worse than normal, it very well could ve been a coincidence that I just so happened to attributed to the Provera since I had just started it.

  4. Based on the above background information, with the goal of investigating novel combinations of molecules that could be detrimental to malaria parasites, this study was focussed on a molecule that targets the apicoplast, doxycycline, on two inhibitors of ABC efflux pumps, verapamil and elacridar, and on ivermectin, a drug that is both interesting as a potential efflux pump inhibitor, as well as it is at the core of parasite control programmes in tropical medicine. tetani organisms elaborate at least two toxins.

  5. Extracted lipids were dried under a gentle stream of nitrogen and reconstituted in 100 ОјL of chloroform for subsequent fatty acid analysis undetermined; no symbol, weak

  6. We observed this occurring in our system at the fiber connection where the DCF fiber from the coupler meets the DCF fiber in the sample arm, providing an opportunity for light to leak into the inner cladding

  7. The cause of Peyronie s disease is unknown, but it may involve injury to the penis that causes local bleeding, which in turn leads to the formation of fibrous tissue

  8. We also have Magnesium which is an essential mineral helping you with your energy levels, muscle strength and stamina Trivieri N, et al

  9. B E Data from n 4 oil treated Esr1 cKO and n 4 tamoxifen treated Esr1 cKO, n 3 oil treated wild type and n 5 tamoxifen treated wild type mice Zhu YY, Si W, Ji TF, Guo XQ, Hu Y, Yang JL

  10. clotrimazole will decrease the level or effect of paromomycin by P glycoprotein MDR1 efflux transporter

  11. It seems far fetched but she wasn t easily persuaded otherwise desmopressin cephalexin monohydrate 500 mg dosage Clearly, Kerry wants it more than Netanyahu or Abbas, said Elliott Abrams, who served as a deputy national security adviser under Republican U

  12. To investigate the effects of these drugs on gene expression in breast cancer cells, we treated estrogen receptor positive MCF 7 cells stably transfected with the aromatase gene known as MCF 7aro cells with testosterone, 17ОІ estradiol, two aromatase inhibitors letrozole and anastrozole, and an antiestrogen tamoxifen

  13. If parous carriers are also at lower risk of BC, the association between rrBSO and reduced BC risk may appear spuriously stronger

  14. It is not known whether there are changes in the risk of serious adverse events based on the differences in PK profiles of EE in women using ORTHO EVRA compared with women using oral contraceptives containing 30 35 mcg of EE

  15. Mouse B cells were isolated from spleen and left unstimulated or stimulated with anti IgM G antibody, CD40 ligand CD40L and interleukin 4 IL 4 for 24 hours before protein extraction and E quantification of protein levels normalized to HSC70

  16. rythmol ciprofloxacin hydrochloride tablets used for Looking across the region, like for like sales growth actually accelerated in the United Kingdom and exceeded more modest comp growth in most of Continental Europe in the second quarter, after seeing the opposite pattern in the first quarter

  17. Switch off time for varying Doxycycline concentrations from experimental data and model predictions A century old warrior who was obviously can you take zaroxolyn and lasix together low blood pressure while on medication stronger than the others stood up and said loudly

  18. A cat on top of the habitat or a dog on the other side of the glass can be stressful for the reptile inside

  19. were amazed when they saw such a magnificent scene, and they were even more curious about what Zhao Ling was doing inside

  20. And I don t mean that I tire easily or need extra sleep The primary outcome of death from any cause or hospitalization for prespecified cardiovascular causes worsening heart failure, myocardial infarction, stroke, atrial or ventricular arrhythmia, and myocardial infarction or stroke occurring during hospitalization for any cause is shown for patients receiving irbesartan and those receiving placebo

  21. Hein Putter Department of Medical Statistics, Leiden University Medical Centre, Leiden, The Netherlands

  22. At the end of the study, the researchers also asked the women about how much change, if any, there was in the amount of joint pain they were having

网站地图