英文:
Multiple tickers in Go's select statement's cases
问题
当我运行以下的Go 1.18代码时,我期望看到两个消息不断地被打印到标准输出,一个接一个地。然而,我只看到"ping"被不断地打印。为什么会这样?select
语句必须执行两个case,因为有两个不同的通道操作,并且这些通道本身是不同的。
for {
select {
case <-time.NewTicker(time.Millisecond * 400).C:
fmt.Println("ping")
case <-time.NewTicker(time.Millisecond * 600).C:
fmt.Println("pong")
}
}
英文:
When I run the following Go 1.18 code, I expect to see both messages being printed repeatedly to standard output, one after another. However, I only see "ping" being printed repeatedly. Why? The select
statement must be executing both cases, since there are two different channel operations, and the channels themselves are different.
for {
select {
case <-time.NewTicker(time.Millisecond * 400).C:
fmt.Println("ping")
case <-time.NewTicker(time.Millisecond * 600).C:
fmt.Println("pong")
}
}
答案1
得分: 2
你正在案例中创建一个新的计时器。选择语句首先评估案例,这意味着它创建了两个计时器,当较短的计时器滴答后,它会创建另一对计时器。下一次循环时,较短的计时器将再次被选择。
在for循环之外创建这两个计时器。
英文:
You are creating a new ticker in the case. The select statement evaluates the cases first, which means, it creates two timers, and after the shorter one ticks, it creates another pair of timers. Next time around, the shorter one will be picked again.
Create the two tickers outside the for loop.
通过集体智慧和协作来改善编程学习和解决问题的方式。致力于成为全球开发者共同参与的知识库,让每个人都能够通过互相帮助和分享经验来进步。
评论