Go 的版本是Go1.20
➜ ~ go version
go version go1.20.4 darwin/arm64
测试代码
package main
import (
"sync"
)
func main() {
var lock sync.Mutex
defer lock.Unlock()
lock.Lock() // 第一次锁定
lock.Lock() // 第二次锁定
}
执行
➜ ~ go run main.go
fatal error: all goroutines are asleep - deadlock!
goroutine 1 [sync.Mutex.Lock]:
sync.runtime_SemacquireMutex(0x140000a0000?, 0x0?, 0x1400009cef8?)
/usr/local/go/src/runtime/sema.go:77 +0x28
sync.(*Mutex).lockSlow(0x140000a0000)
/usr/local/go/src/sync/mutex.go:171 +0x178
sync.(*Mutex).Lock(...)
/usr/local/go/src/sync/mutex.go:90
main.main()
/Users/tu/main.go:11 +0x108
exit status 2
修改测试代码
package main
import (
"sync"
"time"
)
func main() {
var lock sync.Mutex
group := sync.WaitGroup{}
for i := 1; i < 10; i++ {
group.Add(1)
go func() {
defer group.Done()
time.Sleep(10 * time.Second)
}()
}
defer lock.Unlock()
lock.Lock() // 第一次锁定
lock.Lock() // 第二次锁定
group.Wait()
}
执行后阻塞了并没有panic
➜ ~ go run main.go