gpt4 book ai didi

golang超时使用范围从 channel 读取

转载 作者:数据小太阳 更新时间:2023-10-29 03:05:45 24 4
gpt4 key购买 nike

我的代码是这样的:

outChannel := make(chan struct{})
...
for out := range outChannel {
...
}

我有一个生产者写入 outChannel 并希望在读取它时超时(如果整个处理时间超过 XX 秒)。这样做的正确方法是什么?

因为我只看到构造(在:https://github.com/golang/go/wiki/Timeouts)使用select和从 channel 读取的多个case,然而,这似乎不适用于一次使用范围

最佳答案

您想做类似的事情,但对整个循环使用单一超时 channel :

const timeout = 30 * time.Second
outc := make(chan struct{})
timec := time.After(timeout)

RangeLoop:
for {
select {
case <-timec:
break RangeLoop // timed out
case out, ok := <-outc:
if !ok {
break RangeLoop // Channel closed
}
// do something with out
}
}

关于golang超时使用范围从 channel 读取,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/39582403/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com