为什么这个 Golang 代码不能在多个 time.After 通道中进行选择?

为什么这个 Golang 代码不能在多个 time.After 通道中进行选择?


请参阅下面的代码。永远不会发出“超时”消息。为什么?


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


白猪掌柜的
浏览 177回答 2
2回答

森林海

因为time.After是一个函数,所以每次迭代都会返回一个新的通道。如果您希望此通道在所有迭代中都相同,则应在循环之前将其保存:timeout := time.After(3 * time.Second)for {&nbsp; &nbsp; select {&nbsp; &nbsp; //...&nbsp; &nbsp; case <-timeout:&nbsp; &nbsp; &nbsp; &nbsp; fmt.Printf("timeout\n")&nbsp; &nbsp; &nbsp; &nbsp; return&nbsp; &nbsp; }}游乐场:http : //play.golang.org/p/muWLgTxpNf。

叮当猫咪

另一种可能性是使用time.Tick(1e9)每秒生成一个时间刻度,然后timeAfter在指定时间段后侦听频道。package mainimport (&nbsp; &nbsp; "fmt"&nbsp; &nbsp; "time")func main() {&nbsp; &nbsp; count := 0&nbsp; &nbsp; timeTick := time.Tick(1 * time.Second)&nbsp; &nbsp; timeAfter := time.After(5 * time.Second)&nbsp; &nbsp; for {&nbsp; &nbsp; &nbsp; &nbsp; select {&nbsp; &nbsp; &nbsp; &nbsp; case <-timeTick:&nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; count++&nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; fmt.Printf("tick %d\n", count)&nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; if count >= 5 {&nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; fmt.Printf("ugh\n")&nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; return&nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; }&nbsp; &nbsp; &nbsp; &nbsp; case <-timeAfter:&nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; fmt.Printf("timeout\n")&nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; return&nbsp; &nbsp; &nbsp; &nbsp; }&nbsp; &nbsp; }}
打开App,查看更多内容
随时随地看视频慕课网APP

相关分类

Go