有人可以解释一下,为什么如果通道被缓冲,程序不会以fatal_error退出?
无缓冲的频道
package main
func main() {
c := make(chan int)
c <- 3
}
fatal error: all goroutines are asleep - deadlock!
Run Code Online (Sandbox Code Playgroud)
缓冲频道
package main
func main() {
c := make(chan int, 1)
c <- 3
}
[no output]
Program exited.
Run Code Online (Sandbox Code Playgroud)
谢谢!
Sea*_*ean 11
如果缓冲区中有空间,则写入缓冲通道不会阻止.
如果您尝试将两个项目放在缓冲区大小为1的通道中,则会出现相同的错误:
package main
func main() {
c := make(chan int, 1)
c <- 3
c <- 4
}
Run Code Online (Sandbox Code Playgroud)
给你:
fatal error: all goroutines are asleep - deadlock!
Run Code Online (Sandbox Code Playgroud)
谢谢@马特
我在这篇文章中找到了答案make(chan bool) 与 make(chan bool, 1) 的行为有何不同?:
Actually that's the reason why your problem is generated. Un-buffered channels are only writable when there's someone blocking to read from it, which means you shall have some coroutines to work with -- instead of this single one.