【问题标题】:How to execute the `case` in the `select` statement only if some conditions are satisfied只有满足某些条件,如何在`select`语句中执行`case`
【发布时间】:2021-12-30 10:54:00
【问题描述】:

我有一个频道:

aChan := make(chan struct{})

和超时持续时间var t time.Duration。如果通道关闭或达到t 超时,我希望程序退出, 如果 t 是正持续时间

我知道我可以使用外部 if else 循环,但这看起来非常多余:

    if t >= time.Duration(0) {
        select {
        case <-time.After(t):
            fmt.Fprintln(os.Stdout, "timeout!"))
            close(timeoutChan)
        case <-aChan:
            fmt.Fprintln(os.Stdout, "aChan is closed"))
            return
        }
    } else {
        select {
        case <-aChan:
            fmt.Fprintln(os.Stdout, "aChan is closed"))
            return
        }
    }

有没有更优雅的写法?

【问题讨论】:

    标签: go concurrency


    【解决方案1】:

    当持续时间小于零时,使用nil 频道进行超时。 nil 频道的超时情况不会执行,因为nil 频道上的接收永远不会准备好。

    var after <-chan time.Time
    if t >= 0 {
        after = time.After(t)
    }
    select {
    case <-after:
        fmt.Println("timeout!")
        close(timeoutChan)
    case <-aChan:
        fmt.Println("aChan is closed")
        return
    }
    

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多