我绝对是 Golang 的新手。我正在通过 Tour of Go 学习,然后用我自己的理解来实现想法。我在使用 goroutines 时遇到问题。我创建了一个无缓冲 channel ,然后向该 channel 发送了一个字符串。
func main() {
p := make(chan string)
p <- "Hello goroutine"
fmt.Println(<-p)
}
抛出错误
fatal error: all goroutines are asleep - deadlock!
我明白了, channel 是无缓冲的。 (就是这个原因。对吧?)。
但是当我重构 p <- "Hello goroutine
到协程
func main() {
p := make(chan string)
go sendHello(p)
fmt.Println(<-p)
}
func sendHello(p chan string) {
p <- "Hello goroutine"
}
它工作没有问题。我读到在大多数情况下我们不需要使用带有映射、 slice 和 channel 的指针来修改值。 是channel p
传递给 func sendHello(p chan string)
通过具有单独缓冲区的副本。我仍然无法理解它。
最佳答案
请记住, channel 有两个端点,一个是发送者,一个是接收者。您的问题与执行顺序有关。
在第一个示例中,当您使用无缓冲 channel 时,该 channel 需要一个接收器,而没有发送Hello goroutine
消息,并等待直到有一个(缓冲 channel 不是这种情况,因为它不需要等待),并且执行永远不会到达下一行(即死锁)。
但是在第二个例子中,receiver 绑定(bind)到 channel 之后执行 groutine,sender 和 receiver 都没有保持等待状态.
关于go - channel 缓冲区在没有 goroutines 的情况下(在其范围内)与传递给 goroutines 时如何在 golang 中工作?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/53814981/