通道缓冲区在没有 goroutines 的情况下(在其范围内)与传递给 goroutines 时如何在 golang 中工作?
How channel buffers work in golang when used without goroutines (within their scope) vs when they are passed to goroutines?
我绝对是 Golang 的新手。我正在通过 Tour of Go 学习,然后用我自己的理解来实现想法。我在使用 goroutines 时遇到问题。我创建了一个无缓冲通道,然后向该通道发送了一个字符串。
func main() {
p := make(chan string)
p <- "Hello goroutine"
fmt.Println(<-p)
}
抛出错误
fatal error: all goroutines are asleep - deadlock!
我明白了,频道是无缓冲的。 (就是这个原因吧?)。
但是当我将 p <- "Hello goroutine
重构为 goroutine
func main() {
p := make(chan string)
go sendHello(p)
fmt.Println(<-p)
}
func sendHello(p chan string) {
p <- "Hello goroutine"
}
它没有问题。我读到在大多数情况下我们不需要使用带有映射、切片和通道的指针来修改值。 是通过具有单独缓冲区的副本channel p
传递给func sendHello(p chan string)
的。我仍然无法理解它。
请记住,通道有两个端点,发送方和接收方。你的问题是关于执行顺序的。
在第一个示例中,当您使用无缓冲通道时,通道需要一个 接收方 ,而在发送 Hello goroutine
消息时有 none,并等待直到有一个(缓冲通道不是这种情况,因为它不需要等待),并且执行永远不会到达下一行(即死锁)。
但是在第二个例子中,receiver绑定到channel,groutine在之后执行,sender和receiver不要停留在等待状态。
我绝对是 Golang 的新手。我正在通过 Tour of Go 学习,然后用我自己的理解来实现想法。我在使用 goroutines 时遇到问题。我创建了一个无缓冲通道,然后向该通道发送了一个字符串。
func main() {
p := make(chan string)
p <- "Hello goroutine"
fmt.Println(<-p)
}
抛出错误
fatal error: all goroutines are asleep - deadlock!
我明白了,频道是无缓冲的。 (就是这个原因吧?)。
但是当我将 p <- "Hello goroutine
重构为 goroutine
func main() {
p := make(chan string)
go sendHello(p)
fmt.Println(<-p)
}
func sendHello(p chan string) {
p <- "Hello goroutine"
}
它没有问题。我读到在大多数情况下我们不需要使用带有映射、切片和通道的指针来修改值。 是通过具有单独缓冲区的副本channel p
传递给func sendHello(p chan string)
的。我仍然无法理解它。
请记住,通道有两个端点,发送方和接收方。你的问题是关于执行顺序的。
在第一个示例中,当您使用无缓冲通道时,通道需要一个 接收方 ,而在发送 Hello goroutine
消息时有 none,并等待直到有一个(缓冲通道不是这种情况,因为它不需要等待),并且执行永远不会到达下一行(即死锁)。
但是在第二个例子中,receiver绑定到channel,groutine在之后执行,sender和receiver不要停留在等待状态。