gpt4 book ai didi

go - golang什么时候停止处理 channel 并退出程序

转载 作者:行者123 更新时间:2023-12-01 22:40:12 26 4
gpt4 key购买 nike

我正在按自己的时间学习 Go。通过教程。查看下面的代码,无法弄清楚它是如何停止执行的。有人愿意帮忙吗?

package main

import (
"fmt"
)

func main() {
ch1 := make(chan int, 2)
ch1 <- 1
ch1 <- 2
ch2 := make(chan int, 2)
ch2 <- 3
LOOP:
for {
select {
case v1 := <-ch1:
fmt.Println("chan1 val", v1)
case v2 := <-ch2:
fmt.Println("chan2 val", v2)
default:
break LOOP
}
}
}

最佳答案

来自 select documentation .

If one or more of the communications can proceed, a single one that can proceed is chosen via a uniform pseudo-random selection. Otherwise, if there is a default case, that case is chosen. If there is no default case, the "select" statement blocks until at least one of the communications can proceed.



一旦两个 channel 都没有准备好读取,在这种情况下,因为它们已经耗尽, default会跑。 break LOOP跳出标签 for循环 select在里面, main退出,程序终止。

关于go - golang什么时候停止处理 channel 并退出程序,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/61898399/

26 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com