golang死锁
package main
import (
"fmt"
"sync"
"time"
)
var (
x,y int
wg sync.WaitGroup
lockX sync.Mutex //用来锁变量x
lockY sync.Mutex //用来锁变量y
)
func LockA() {
defer wg.Done()
lockX.Lock() //将x锁住
x++
time.Sleep(time.Second) //给函数LockB时间,用来锁住y
lockY.Lock() //将y锁住
y++
lockY.Unlock()
lockX.Unlock()
}
func LockB() {
defer wg.Done()
lockY.Lock() //将y锁住
y++
time.Sleep(time.Second) //给函数LockA时间,用来锁住x
lockX.Lock() //将x锁住
x++
lockX.Unlock()
lockY.Unlock()
}
func main() {
wg.Add(2)
go LockA()
go LockB()
wg.Wait()
fmt.Println("x = ", x)
fmt.Println("y = ", y)
}
运行结果:
fatal error: all goroutines are asleep - deadlock!
goroutine 1 [semacquire]:
sync.runtime_Semacquire(0x0)