Go语言的select语句的case中可以包含多个ticker。

huangapple go评论79阅读模式
英文:

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 &lt;-time.NewTicker(time.Millisecond * 400).C:
		fmt.Println(&quot;ping&quot;)
	case &lt;-time.NewTicker(time.Millisecond * 600).C:
		fmt.Println(&quot;pong&quot;)
	}
}

答案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.

huangapple
  • 本文由 发表于 2022年5月26日 08:15:19
  • 转载请务必保留本文链接:https://go.coder-hub.com/72385397.html
匿名

发表评论

匿名网友

:?: :razz: :sad: :evil: :!: :smile: :oops: :grin: :eek: :shock: :???: :cool: :lol: :mad: :twisted: :roll: :wink: :idea: :arrow: :neutral: :cry: :mrgreen:

确定