[英]Go channel deadlock is not happening
package main
import (
"fmt"
"time"
)
func main() {
c := make(chan int)
go func() {
fmt.Println("hello")
c <- 10
}()
time.Sleep(2 * time.Second)
}
In the above program, I have created a Go routine which is writing to channel c but there is no other go routine which is reading from the channel.在上面的程序中,我创建了一个 Go 例程,它正在写入通道 c 但没有其他 go 例程正在从通道中读取。 Why isnt there a deadlock in this case?
为什么在这种情况下没有死锁?
A deadlock implies all goroutines being blocked, not just one arbitrary goroutine of your choosing.死锁意味着所有 goroutine 都被阻塞,而不仅仅是您选择的一个任意 goroutine。
The main
goroutine is simply in a sleep, once that is over, it can continue to run. main
goroutine 只是处于休眠状态,一旦结束,它就可以继续运行。
If you switch the sleep
with a select{}
blocking forever operation, you'll get your deadlock:如果您使用
select{}
永久阻塞操作切换sleep
,您将遇到死锁:
c := make(chan int)
go func() {
fmt.Println("hello")
c <- 10
}()
select {}
Try it on the Go Playground .在Go 游乐场上试一试。
See related: Why there is no error that receiver is blocked?参见相关: 为什么没有接收器被阻塞的错误?
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.