为什么这个Golang代码不能在多个时间内进行选择.通道工作后?

Eve*_*ton 8 time timeout channel go

为什么这个Golang代码不能在多个时间内进行选择.通道工作后?

见下面的代码.永远不会发出"超时"消息.为什么?

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
        }
    }
}
Run Code Online (Sandbox Code Playgroud)

在Playground上运行:http://play.golang.org/p/1gku-CWVAh

输出:

tick 1
tick 2
tick 3
tick 4
tick 5
ugh
Run Code Online (Sandbox Code Playgroud)

Ain*_*r-G 12

因为它time.After是一个函数,所以在每次迭代时它返回一个新的通道.如果您希望此通道对于所有迭代都相同,则应在循环之前保存它:

timeout := time.After(3 * time.Second)
for {
    select {
    //...
    case <-timeout:
        fmt.Printf("timeout\n")
        return
    }
}
Run Code Online (Sandbox Code Playgroud)

游乐场:http://play.golang.org/p/muWLgTxpNf.


End*_*imo 5

甚至@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
        }
    }
}
Run Code Online (Sandbox Code Playgroud)