go 中的非阻塞通道操作。发送?

Non-blocking channel operations in go. Send?

我正在经历 Go by Example: Non-Blocking Channel Operations

据我了解,第一个select触发了default案例,因为messages通道中没有任何内容,如果default案例没有' 存在,我们会收到 fatal error: all goroutines are asleep - deadlock! 错误,对吗?

嗯,我不知道怎么触发第二个 select,特别是触发 case messages <- msg:

正如我所想,它应该与接收相反。因此,如果有 2 条消息的缓冲区并且我们将第 3 条消息发送到通道,它会触发 default 子句,但是 messages 通道是空的,所以为什么在第二个 select它会触发 default 子句吗?我怎样才能触发 case messages <- msg: 子句?

why in the second select does it trigger the default clause?

因为通道是无缓冲的,并且没有其他 go routine 在接收时被阻塞。

how can I trigger the case messages <- msg: clause?

您可以:

  1. 使messages缓冲

    messages := make(chan string, 1)
    

    https://play.golang.org/p/b1aO6N-dYf

  2. 创建另一个在接收时被阻止的 go 例程

    go func() {
        fmt.Println("Received from other go routine", <-messages)
    }()
    

    https://play.golang.org/p/Z7e1ZcO3C5