为什么在多个 time.After 通道中 select 的 Golang 代码不起作用?
Why doesn't this Golang code to select among multiple time.After channels work?
为什么这个 Golang 代码到 select 在多个 time.After 通道中不起作用?
见下面的代码。 'timeout' 消息永远不会发出。为什么?
package main
import (
"fmt"
"time"
)
func main() {
count := 0
for {
select {
case <-time.After(1 * time.Second):
count++
fmt.Printf("tick %d\n", count)
if count >= 5 {
fmt.Printf("ugh\n")
return
}
case <-time.After(3 * time.Second):
fmt.Printf("timeout\n")
return
}
}
}
运行 它在 Playground 上:http://play.golang.org/p/1gku-CWVAh
输出:
tick 1
tick 2
tick 3
tick 4
tick 5
ugh
因为time.After
是一个函数,所以在每次迭代中它returns一个新的通道。如果你希望这个通道对于所有迭代都是相同的,你应该在循环之前保存它:
timeout := time.After(3 * time.Second)
for {
select {
//...
case <-timeout:
fmt.Printf("timeout\n")
return
}
}
即使@Ainar-G已经给出了答案,另一种可能是使用time.Tick(1e9)
每秒生成一个时间刻度,然后在指定时间段后监听timeAfter
频道。
package main
import (
"fmt"
"time"
)
func main() {
count := 0
timeTick := time.Tick(1 * time.Second)
timeAfter := time.After(5 * time.Second)
for {
select {
case <-timeTick:
count++
fmt.Printf("tick %d\n", count)
if count >= 5 {
fmt.Printf("ugh\n")
return
}
case <-timeAfter:
fmt.Printf("timeout\n")
return
}
}
}
为什么这个 Golang 代码到 select 在多个 time.After 通道中不起作用?
见下面的代码。 'timeout' 消息永远不会发出。为什么?
package main
import (
"fmt"
"time"
)
func main() {
count := 0
for {
select {
case <-time.After(1 * time.Second):
count++
fmt.Printf("tick %d\n", count)
if count >= 5 {
fmt.Printf("ugh\n")
return
}
case <-time.After(3 * time.Second):
fmt.Printf("timeout\n")
return
}
}
}
运行 它在 Playground 上:http://play.golang.org/p/1gku-CWVAh
输出:
tick 1
tick 2
tick 3
tick 4
tick 5
ugh
因为time.After
是一个函数,所以在每次迭代中它returns一个新的通道。如果你希望这个通道对于所有迭代都是相同的,你应该在循环之前保存它:
timeout := time.After(3 * time.Second)
for {
select {
//...
case <-timeout:
fmt.Printf("timeout\n")
return
}
}
即使@Ainar-G已经给出了答案,另一种可能是使用time.Tick(1e9)
每秒生成一个时间刻度,然后在指定时间段后监听timeAfter
频道。
package main
import (
"fmt"
"time"
)
func main() {
count := 0
timeTick := time.Tick(1 * time.Second)
timeAfter := time.After(5 * time.Second)
for {
select {
case <-timeTick:
count++
fmt.Printf("tick %d\n", count)
if count >= 5 {
fmt.Printf("ugh\n")
return
}
case <-timeAfter:
fmt.Printf("timeout\n")
return
}
}
}