为什么在 Golang 中发送大于缓冲通道大小的值会导致死锁错误?

sof*_*fs1 2 channel go goroutine

// By default channels are _unbuffered_, meaning that they
// will only accept sends (`chan <-`) if there is a
// corresponding receive (`<- chan`) ready to receive the
// sent value. _Buffered channels_ accept a limited
// number of  values without a corresponding receiver for
// those values.

package main

import "fmt"

func main() {

    // Here we `make` a channel of strings buffering up to
    // 2 values.
    messages := make(chan string, 2)

    // Because this channel is buffered, we can send these
    // values into the channel without a corresponding
    // concurrent receive.
    messages <- "buffered"
    messages <- "channel"
    messages <- "channel1" //I added this. 

    // Later we can receive these two values as usual.
    fmt.Println(<-messages)
    fmt.Println(<-messages)
}
Run Code Online (Sandbox Code Playgroud)

它抛出的错误:

fatal error: all goroutines are asleep - deadlock!

goroutine 1 [chan send]:
main.main()
    /tmp/sandbox795158698/prog.go:23 +0x8d
Run Code Online (Sandbox Code Playgroud)

问题:

  1. 我们不能发送比缓冲区大小更多的值吗?
  2. 为什么错误显示“所有 goroutine 都在睡觉 - 死锁!” 当代码中没有 goroutine 时?
  3. 为什么会陷入这样的僵局呢?请解释?

游乐场链接

Bur*_*dar 9

尝试写入完整通道将会阻塞,直到其他 goroutine 从中读取数据。在你的程序中,没有其他 goroutine。因此,当您写入完整通道时,主 Goroutine 会阻塞,并且由于没有其他 Goroutine,因此主 Goroutine 不可能继续前进。这是一个僵局。