【发布时间】:2018-10-02 03:29:48
【问题描述】:
这是一个关于无缓冲通道的简单示例代码:
ch01 := make(chan string)
go func() {
fmt.Println("We are in the sub goroutine")
fmt.Println(<-ch01)
}()
fmt.Println("We are in the main goroutine")
ch01 <- "Hello"
我得到的结果:
We are in the main goroutine
We are in the sub goroutine
Hello
去游乐场: https://play.golang.org/p/rFWQbwXRzGw
据我了解,发送操作阻塞了主协程,直到子协程在通道ch01 上执行接收操作。然后程序就退出了。
在发送操作之后放置 sub goroutine 之后:
fmt.Println("We are in the main goroutine")
ch01 <- "Hello"
go func() {
fmt.Println("We are in the sub goroutine")
fmt.Println(<-ch01)
}()
发生了死锁:
We are in the main goroutine
fatal error: all goroutines are asleep - deadlock!
去游乐场 https://play.golang.org/p/DmRUiBG4UmZ
这次发生了什么?这是否意味着在ch01 <- "Hello" 之后主 goroutine 立即被阻塞,以至于子 goroutine 没有机会运行?如果是真的,我应该如何理解第一个代码示例的结果?(首先在 main goroutine 中,然后在 sub goroutine 中)。
【问题讨论】:
标签: go