Go语言 互斥锁 sync.Mutex 妙用 | Konica 的自留地

Go语言 互斥锁 sync.Mutex 妙用

Box, Card, Celebrate, Celebration, Christmas, Decorate

sync.Mutex 互斥锁

sync.Mutex 的 Lock 方法是可以在多个 goruotine 调用的, 以前理解错
只要不是死锁就行

示例

Go语言代码:

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
package main
import (
"fmt"
"sync"
"time"
)
func main() {
var mu sync.Mutex
go func() {
fmt.Println(1, "prepare lock")
mu.Lock()
fmt.Println(1, "locked, sleeping 2s")
time.Sleep(2e9)
mu.Unlock()
fmt.Println(1, "unlocked")
}()
go func() {
fmt.Println(2, "prepare lock")
mu.Lock()
fmt.Println(2, "locked, sleeping 1s")
time.Sleep(1e9)
mu.Unlock()
fmt.Println(2, "unlocked")
}()
time.Sleep(4e9)
}

运行结果:

1 prepare lock
1 locked, sleeping 2s
2 prepare lock
1 unlocked
2 locked, sleeping 1s
2 unlocked