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)
    }
    
    本回答被题主选为最佳回答 , 对您是否有帮助呢?
    评论

报告相同问题?

悬赏问题

  • ¥20 机器学习能否像多层线性模型一样处理嵌套数据
  • ¥20 西门子S7-Graph,S7-300,梯形图
  • ¥50 用易语言http 访问不了网页
  • ¥50 safari浏览器fetch提交数据后数据丢失问题
  • ¥15 matlab不知道怎么改,求解答!!
  • ¥15 永磁直线电机的电流环pi调不出来
  • ¥15 用stata实现聚类的代码
  • ¥15 请问paddlehub能支持移动端开发吗?在Android studio上该如何部署?
  • ¥20 docker里部署springboot项目,访问不到扬声器
  • ¥15 netty整合springboot之后自动重连失效