Goroutines 选择范围循环

标签 go concurrency channel goroutine

<分区>

我想生成一个 goroutine 来监听 chan intchan os.Signal 类型的两个 channel 。我希望行为具体取决于在任一 channel 上收到的内容。这意味着一些 os.Signal 可能会导致 os.exit() 而有些可能不会,一些 int 通过 chan int 接收> 可能会打印一条语句,有些可能会调用一个函数,所以我需要这个 gorountine 一直运行,因为行为是不同的。我希望这一切都由一个函数处理。

我很难弄清楚如何在句法上实现这一目标。我似乎不能在 select block 中使用 range 循环,也不能在 a 中使用 select block range 循环。我在网上找不到任何资源。有人可以给我举个例子吗?

最佳答案

你可以放一个select statementfor 循环中(这是语言规范中的示例之一)。与 for...range 循环不同,这将让您从两个 channel 读取。如果其中一个 channel 关闭,它也不会自动终止。当你receive from a closed channel ,一个关闭的 channel 总是准备好接收并且总是产生一个零值,并且它有一个二值形式告诉你 channel 是否打开。

你的函数可能看起来像

func HandleStuff(numbers <-chan int, signals <-chan os.Signal) {
    var goingToExit bool
    for {
        select {
        case n := <-numbers:
            if n == 0 {
                fmt.Printf("zero\n")
            } else if n == 1 {
                goingToExit = true
            }
        case sig, ok := <-signals:
            if !ok { // the channel is closed
                return
            } else if goingToExit {
                os.Exit(0)
            }
        }
    }
}

关于Goroutines 选择范围循环,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/53734488/

相关文章:

regex - Go validator.v2 为正则表达式给出错误 "unknown tag"

Java volatile 重排序预防作用域

concurrency - 为什么并发写入的boolean值设置为false后还是true?

java - Android (Java) : Parse. com 没有订阅不是硬编码字符串的 channel ?

Golang嵌套类在函数内

go - golang 字节数组的大小

math - Golang 中的大 Int 添加

c# - 互斥存储过程

go - 阅读 channel 的不同方式

go - 解决 goroutines 死锁