[英]Golang race condition when sharing channel across parallel goroutines
[英]How channel buffers work in golang when used without goroutines (within their scope) vs when they are passed to goroutines?
我绝对是Golang的新手。 我正在通过环游学习,然后以自己的理解实施想法。 我在使用goroutines时遇到问题。 我创建了一个无缓冲的通道,然后向该通道发送了一个字符串。
func main() {
p := make(chan string)
p <- "Hello goroutine"
fmt.Println(<-p)
}
引发错误
致命错误:所有goroutine都在睡着-死锁!
我明白了,通道是无缓冲的。 ( 这就是原因。对吗? )。
但是当我将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
消息时一直没有接收器 ,并等待直到有一个接收器为止(缓冲通道不是这种情况,因为它不需要等待),执行将永远不会到达下一行(即死锁)。
但是在第二个示例中,接收者绑定到通道,并且在之后执行常规程序,并且发送者和接收者都不会保持等待状态。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.