Go通道死锁没有发生

Go channel deadlock is not happening

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。

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

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

c := make(chan int)

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

select {}

Go Playground 上试用。

查看相关内容: