【问题标题】:Golang timeout is not executed with channelsGolang 超时不与通道一起执行
【发布时间】:2016-04-25 23:55:36
【问题描述】:

我正在使用 goroutines/channels。 这是我的代码。 为什么超时情况没有被执行?

func main() {
    c1 := make(chan int, 1)

    go func() {
        for {
            time.Sleep(1500 * time.Millisecond)
            c1 <- 10
        }
    }()

    go func() {
        for {
            select {
            case i := <-c1:
                fmt.Println(i)
            case <-time.After(2000 * time.Millisecond):
                fmt.Println("TIMEOUT") // <-- Not Executed
            }
        }
    }()

    fmt.Scanln()
}

【问题讨论】:

    标签: go timeout channel channels


    【解决方案1】:

    您的超时不会发生,因为您的一个 goroutine 每隔 1.5 秒(左右)在您的 c1 通道上重复发送一个值,并且只有在没有从 @ 接收到值时才会发生超时987654322@ 2 秒。

    一旦从c1 接收到一个值,在下一次执行select 的迭代中,将再次调用new time.After(),它会返回一个new仅在另外 2 秒后才会在其上发送值的通道。先前select 执行的超时通道被丢弃,不再使用。

    要在2秒后接收超时,只创建一次超时通道,例如:

    timeout := time.After(2000 * time.Millisecond)
    for {
        select {
        case i := <-c1:
            fmt.Println(i)
        case <-timeout:
            fmt.Println("TIMEOUT") // Will get executed after 2 sec
        }
    }
    

    输出:

    10
    TIMEOUT
    10
    10
    10
    ...
    

    【讨论】:

      猜你喜欢
      • 2019-01-30
      • 1970-01-01
      • 1970-01-01
      • 2017-12-08
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2015-06-25
      相关资源
      最近更新 更多