我知道这是错的
func e6() {
c1 := make(chan struct{}, 1)
<-c1
go func() {
c1 <- struct{}{}
}()
}
这是对的
func e6() {
c1 := make(chan struct{}, 1)
go func() { //statement1
c1 <- struct{}{}
}()
<-c1 //statement2
}
由于我们无法假定正确示例中statement1 和statement2 的顺序,如果statement2 先于statement1 执行怎么办,在这种情况下,正确的示例看起来就像是错误的示例,但为什么是正确的呢?谢谢你帮助我。
最佳答案
实际上,生成 goroutine 后会发生以下情况:首先执行 goroutine 并填充 channel ,以便您可以立即从中读取 (<-c1
)。或者 read 语句先执行,但由于没有从该 channel 读取的内容,它会等待直到可以读取某些内容(“它阻塞”)。现在 goroutine 调度程序启动,注意到两个 goroutine 中的一个阻塞并且它“最终”执行另一个 goroutine,它填充 channel 并退出,使阻塞 goroutine 成为唯一剩下的,因此它再次获得执行时间。但现在 channel 已填充,可以从中读取, channel 中的值被读取为空,原始 goroutine 继续,结束函数。
请注意,这有点简化,您绝对应该阅读 goroutines。
关于go - 如何确保向 channel 发送消息的顺序正确,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/46724157/