【问题标题】:How can I use 'time.After' and 'default' in Golang?如何在 Golang 中使用“time.After”和“default”?
【发布时间】:2017-01-05 20:15:06
【问题描述】:

我正在尝试理解 Golang 例程的简单代码:

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
        }
    }

}

很好,但是为什么我不能在这个“选择”块中使用简单的默认值?像这样的:

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.")
    }
}

它得到这个输出:

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

我不明白为什么。

【问题讨论】:

  • 这就是default 所做的。你能解释一下你预计会发生什么吗?
  • 我希望default 这样做,而time.After 的时间还没有结束。
  • 我不明白,这就是它的作用。 time.After 的情况不会执行,因为采用了默认情况。
  • 如果之前有time.After的情况,为什么要采取default

标签: go goroutine


【解决方案1】:

每次执行time.After(4 * time.Second) 时,都会创建一个新的计时器通道。 select 语句无法记住它在上一次迭代中选择的通道。您还采用了异步操作并将其变成了一个繁忙的循环,从而违背了select 语句的目的。

您只需要围绕您感兴趣的两个频道进行简单的选择。它根本不需要循环。

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

如果您真的想多次轮询,请将计时器设置在 for 循环之外,以便每次迭代都检查相同的计时器

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)
}

【讨论】:

  • 谢谢,我知道了
  • 关于最后一部分(for/select),真的是这样吗?我的意思是,time.Sleep 处于阻塞状态,因此在此期间到达的任何“endSignal”都不会被立即处理。
  • @MrFuppes:没错,如果您想立即对endSignal 采取行动,您可以像第一个示例一样使用time.After
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2019-04-30
  • 2019-06-07
  • 2016-05-04
  • 2015-11-03
  • 2022-01-20
相关资源
最近更新 更多