具有范围循环的 Goroutines select
Goroutines select with range loop
我想生成一个 goroutine 来监听 chan int
和 chan os.Signal
类型的两个通道。我希望行为具体取决于在任一渠道上收到的内容。这意味着一些 os.Signal
可能会导致 os.exit()
而有些可能不会,通过 chan int
收到的一些 int
可能会打印一条语句,有些可能会调用一个函数,所以我需要这个 gorountine总是 运行 因为行为不同。我希望这一切都由一个函数处理。
我很难弄清楚如何在语法上实现这一目标。似乎我不能在 select
块内有 range
循环,我也不能在 range
循环内有 select
块。我在网上找不到任何资源。有人可以给我举个例子吗?
你可以放一个select
statement in a for
loop (this is one of the examples in the language spec). Unlike a for...range
loop, this will let you read from both channels. It also won't automatically terminate if one of the channels closes. When you receive from a closed 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)
}
}
}
}
我想生成一个 goroutine 来监听 chan int
和 chan os.Signal
类型的两个通道。我希望行为具体取决于在任一渠道上收到的内容。这意味着一些 os.Signal
可能会导致 os.exit()
而有些可能不会,通过 chan int
收到的一些 int
可能会打印一条语句,有些可能会调用一个函数,所以我需要这个 gorountine总是 运行 因为行为不同。我希望这一切都由一个函数处理。
我很难弄清楚如何在语法上实现这一目标。似乎我不能在 select
块内有 range
循环,我也不能在 range
循环内有 select
块。我在网上找不到任何资源。有人可以给我举个例子吗?
你可以放一个select
statement in a for
loop (this is one of the examples in the language spec). Unlike a for...range
loop, this will let you read from both channels. It also won't automatically terminate if one of the channels closes. When you receive from a closed 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)
}
}
}
}