
我写了一些代码来学习go通道,如下所示的一段代码:
func main(){
intChan := make(chan int, 1)
strChan := make(chan string, 1)
intChan <- 3
strChan <- "hello"
fmt.Println("send")
// comment this, fatal error: all goroutines are asleep - deadlock!
// close(intChan)
// close(strChan)
for {
select {
case e, ok := <-intChan:
time.Sleep(time.Second * 2)
fmt.Println("The case intChan ok: ", ok)
fmt.Println("The case intChan is selected.", e)
case e, ok := <-strChan:
time.Sleep(time.Second)
fmt.Println("The case strChan ok: ", ok)
fmt.Println("The case strChan is selected.", e)
}
}
}如果我注释掉 close() 函数,“for”语句就会被阻塞,正如错误提示“all goroutine are sleep - deadlock!”,这似乎是合理的。
如果我取消注释 close(),“for”语句永远不会停止。接收方从通道获取默认值 0 和 nil,并且从不阻塞。
即使我没有向通道发送任何内容,并在定义通道后调用 close() 。接收器永远不会阻塞或导致任何错误。
立即学习“go语言免费学习笔记(深入)”;
我对 close 函数的作用感到困惑,它是否启动一个 go 例程将特定类型的默认值发送到通道,并且永远不会停止?
当频道关闭时,您仍然可以阅读它,但您的 ok 将为 false。所以,这就是为什么你的 for 永远不会停止。并且,您需要通过条件 if !ok {break } 来中断 for 语句。
当通道未关闭时,当您尝试从中读取数据时,它会被阻塞或不被阻塞,具体取决于缓冲/非缓冲通道。
缓冲通道:您指定大小 (make(chan int, 1))。
无缓冲通道:您没有给出大小 (make(chan int))
在您评论 close 的情况下,它将从您缓冲的通道读取数据一次,因为您通过 intchan <- 3 和 strchan <- "hello" 将数据发送到通道。因此,您将看到控制台打印以下结果。
send the case strchan ok: true the case strchan is selected. hello the case intchan ok: true the case intchan is selected. 3
但是,此后,两个缓冲通道都不再有数据。然后,如果您尝试读取它,您将被阻止,因为缓冲通道中没有任何数据。 (实际上,无缓冲也是没有数据时的情况。)
然后,你会得到 all goroutine are sleep - deadlock 因为主 goroutine 被阻塞以等待来自通道的数据。顺便说一句,当你运行这个程序时,它会启动一个主 goroutine 来运行你的代码。如果只有一个主 goroutine 被阻塞,那就意味着没有人可以帮助你运行你的代码。
您可以在for语句之前添加以下代码。
go func() {
fmt.Println("another goroutine")
for {}
}()
你会发现你没有遇到死锁,因为仍然有一个 goroutine“可能”运行你的代码。
以上就是当golang关闭通道时,接收者goroutine永远不会被阻塞的详细内容,更多请关注php中文网其它相关文章!
每个人都需要一台速度更快、更稳定的 PC。随着时间的推移,垃圾文件、旧注册表数据和不必要的后台进程会占用资源并降低性能。幸运的是,许多工具可以让 Windows 保持平稳运行。
Copyright 2014-2025 https://www.php.cn/ All Rights Reserved | php.cn | 湘ICP备2023035733号