前阵子在做Mit6.824的lab时不知啥情况整个程序突然阻塞,查了好久发现原来是对通道使用不当出了问题。

头图来源:frame-Nengoro(ネんごろぅ)-pixiv


首先看如下代码

func main() {
    c:=make(chan bool)
    c<-true
    fmt.Println(<-c)
    
}

运行结果如下

$ go run main.go
fatal error: all goroutines are asleep - deadlock!
goroutine 1 [chan send]:
main.main()
        main.go:14 +0x37
exit status 2

注意到c是一个没有缓冲区的通道,因此如果在同一个协程内读写该通道则会引发死锁,因为通道没有缓冲区,而读写操作是串行执行,上面的代码中对通道的读操作在写操作之后从而引发了死锁。要解决以上情况造成的死锁有两种办法:
1.为通道申请缓冲区

func main() {
    c:=make(chan bool,1)
    c<-true
    fmt.Println(<-c)
    
}

2.并发执行读写

func main() {
    c:=make(chan bool)
    go func(){
        c<-true
    }()
    fmt.Println(<-c)
    
}
Last modification:July 8th, 2022 at 10:18 pm
If you think my article is useful to you, please feel free to appreciate