【发布时间】:2020-08-14 03:44:29
【问题描述】:
// 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)
}
它抛出的错误:
fatal error: all goroutines are asleep - deadlock!
goroutine 1 [chan send]:
main.main()
/tmp/sandbox795158698/prog.go:23 +0x8d
问题:
- 我们不能发送比缓冲区大小更多的值吗?
- 为什么会出现错误 “所有的 goroutine 都在睡觉——死锁!”当没有 goroutines 时 在代码中?
- 为什么这是一个僵局?请解释一下?
【问题讨论】: