go - 具有 channel 参数的函数中的死锁

标签 go channel goroutine

给定以下简单的 Go 程序:

ch := make(chan int)
go fmt.Println(<- ch)
ch <- 2

如果我替换 go fmt.Println(<- ch)go func(){fmt.Println(<-ch)}() , 效果很好。

但是对于原始版本我得到:

fatal error: all goroutines are asleep - deadlock!

为什么?

最佳答案

spec 中所定义:

The function value and parameters are evaluated as usual in the calling goroutine, but unlike with a regular call, program execution does not wait for the invoked function to complete. Instead, the function begins executing independently in a new goroutine. When the function terminates, its goroutine also terminates. If the function has any return values, they are discarded when the function completes.

所以 <-ch被评估。但它不能,因为 channel 是空的,因此它会阻塞,直到有东西写入它。但是从来没有任何东西写入它,因此这是一个死锁。

当您将其包装在匿名函数中时 - 会发生同样的情况,但对于匿名函数。然后它的主体被同时评估到主 goroutine。

关于go - 具有 channel 参数的函数中的死锁,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/55195033/

相关文章:

ssl - 如何显示网站证书的公钥

go - 为什么 struct byteCounter 被视为 "io.Writer"?

go - 无缓冲 channel 是否等待数据?

stream - 概念 : Channel vs. 流

go - 协程和 `goto` 之间的区别?

go - 为什么 goroutine 会泄漏

go - golang channel 收不到

go - 具有回退功能的汇编函数实现

go - 在 golang 中将一个函数类型转换为另一个函数

asynchronous - 在golang中,如何编写一个为下一阶段引入延迟的流水线阶段?