得到错误:所有goroutines都睡着了 - 死锁

Ale*_*lex 1 go

怎么这样简单的东西不起作用?

c1 := make(chan string)
c1 <- "foo"
fmt.Println(<-c1)
Run Code Online (Sandbox Code Playgroud)

但如果我把它放在一个常规程序中它有效吗?

c1 := make(chan string)
go func() {
    c1 <- "foo"
}()
fmt.Println(<-c1)
Run Code Online (Sandbox Code Playgroud)

这个问题可能看似简单而愚蠢,但我试图理解为什么我不能这样做,在这种情况下我不知道有什么更好的问题.

Cer*_*món 7

通道c1是无缓冲通道.只有当发送方和接收方都准备就绪时,才能在无缓冲信道上成功通信.

线路c1 <- "foo永远阻塞,因为没有接收器就绪.

具有goroutine的程序可以工作,因为发送和接收goroutine运行到发送方和接收方都准备就绪的位置.

该计划也将起作用:

c2 := make(chan string, 1) // <-- note channel size of one
c2 <- "foo"
fmt.Println(<-c2)
Run Code Online (Sandbox Code Playgroud)

通道c2在此程序中缓冲.发送c2 <- "foo"继续,因为缓冲区未满.