首页 > 文章列表 > Go 通道死锁没有发生

Go 通道死锁没有发生

golang
333 2023-03-08

问题内容

package main
import (
    "fmt"
    "time"
)

func main() {
    c := make(chan int)

    go func() {
        fmt.Println("hello")
        c <- 10
    }()

    time.Sleep(2 * time.Second)
}

在上面的程序中,我创建了一个正在写入通道 c 的 Go 例程,但没有其他从通道读取的 Go 例程。为什么在这种情况下没有死锁?

正确答案

死锁意味着所有 goroutine 都被阻塞,而不仅仅是您选择的一个任意 goroutine。

goroutine 只是处于休眠状态,main一旦结束,它就可以继续运行。

如果您sleep使用select{}永久阻塞操作切换,您将遇到死锁:

c := make(chan int)

go func() {
    fmt.Println("hello")
    c <- 10
}()

select {}

在Go Playground上尝试一下。

参见相关:[为什么没有接收器被阻塞的错误?](https://stackoverflow.com/questions/59750056/why-there- is-no-error-that-receiver-is-blocked/59750111#59750111)