为什么这个Golang代码不能在多个时间内进行选择.

为什么这个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
        }
    }
}

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

输出

tick 1
tick 2
tick 3
tick 4
tick 5
ugh
因为time.After是一个函数,所以在每次迭代时它返回一个新的通道.如果您希望此通道对于所有迭代都相同,则应在循环之前保存它:
timeout := time.After(3 * time.Second)
for {
    select {
    //...
    case <-timeout:
        fmt.Printf("timeout\n")
        return
    }
}

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

相关文章

什么是Go的接口? 接口可以说是一种类型,可以粗略的理解为他...
1、Golang指针 在介绍Golang指针隐式间接引用前,先简单说下...
1、概述 1.1&#160;Protocol buffers定义 Protocol buffe...
判断文件是否存在,需要用到"os"包中的两个函数: os.Stat(...
1、编译环境 OS :Loongnix-Server Linux release 8.3 CPU指...
1、概述 Golang是一种强类型语言,虽然在代码中经常看到i:=1...