dqe55175 2016-08-29 17:57
浏览 139
已采纳

如何在Golang中使用“ time.After”和“ default”?

I'm trying to understand a simple code of Golang routines:

package main

import (
    "fmt"
    "time"
)

func sleep(seconds int, endSignal chan<- bool) {
    time.Sleep(time.Duration(seconds) * time.Second)
    endSignal <- true
}

func main() {
    endSignal := make(chan bool, 1)
    go sleep(3, endSignal)
    var end bool

    for !end {
        select {
        case end = <-endSignal:
            fmt.Println("The end!")
        case <-time.After(5 * time.Second):
            fmt.Println("There's no more time to this. Exiting!")
            end = true
        }
    }

}

That's fine, but Why I cannot use a simple default in this "select" block? Something like this:

for !end {
    select {
    case end = <-endSignal:
        fmt.Println("The end.")
    case <-time.After(4 * time.Second):
        fmt.Println("There's no more time to this. Exiting!")
        end = true
    default:
        fmt.Println("No end signal received.")
    }
}

It gets this output:

❯ go run goroutines-timeout.go
No end signal received!
No end signal received!
No end signal received!
No end signal received!
...
The end!

And I can't understand why.

  • 写回答

1条回答 默认 最新

  • dtrnish3637 2016-08-29 18:18
    关注

    Each time you execute time.After(4 * time.Second) you create a new timer channel. There's no way the select statement can remember the channel it selected on in the previous iteration. You've also taken what was an asynchronous operation and turned it into a busy loop, defeating the purpose of the select statement.

    All you need is a a simple select around the two channels you're interested in. It doesn't need to loop at all.

    select {
    case <-endSignal:
        fmt.Println("The end!")
    case <-time.After(4 * time.Second):
        fmt.Println("There's no more time to this. Exiting!")
    }
    

    https://play.golang.org/p/jb4EE8e6cw

    If you really want to poll multiple times, make the timer outside of the for loop, so that the same one is checked each iteration

    timeout := time.After(5 * time.Second)
    pollInt := time.Second
    
    for {
        select {
        case <-endSignal:
            fmt.Println("The end!")
            return
        case <-timeout:
            fmt.Println("There's no more time to this. Exiting!")
            return
        default:
            fmt.Println("still waiting")
        }
        time.Sleep(pollInt)
    }
    
    本回答被题主选为最佳回答 , 对您是否有帮助呢?
    评论

报告相同问题?

悬赏问题

  • ¥15 乌班图ip地址配置及远程SSH
  • ¥15 怎么让点阵屏显示静态爱心,用keiluVision5写出让点阵屏显示静态爱心的代码,越快越好
  • ¥15 PSPICE制作一个加法器
  • ¥15 javaweb项目无法正常跳转
  • ¥15 VMBox虚拟机无法访问
  • ¥15 skd显示找不到头文件
  • ¥15 机器视觉中图片中长度与真实长度的关系
  • ¥15 fastreport table 怎么只让每页的最下面和最顶部有横线
  • ¥15 java 的protected权限 ,问题在注释里
  • ¥15 这个是哪里有问题啊?