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

如何在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)
    }
    
    已采纳该答案
    打赏 评论

相关推荐 更多相似问题