golang超时使用范围从通道读取
golang timing out reading from channel using range
我的代码如下所示:
outChannel := make(chan struct{})
...
for out := range outChannel {
...
}
我有一个生产者写入 outChannel
并希望在读取它时超时(如果整个处理时间超过 XX 秒)。
这样做的正确方法是什么?
因为我只看到构造(位于:https://github.com/golang/go/wiki/Timeouts)使用 select
和多个 case
从频道读取,但是,一旦使用 [= 这似乎不适用14=].
您想做类似的事情,但对整个循环使用单个超时通道:
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
}
}
我的代码如下所示:
outChannel := make(chan struct{})
...
for out := range outChannel {
...
}
我有一个生产者写入 outChannel
并希望在读取它时超时(如果整个处理时间超过 XX 秒)。
这样做的正确方法是什么?
因为我只看到构造(位于:https://github.com/golang/go/wiki/Timeouts)使用 select
和多个 case
从频道读取,但是,一旦使用 [= 这似乎不适用14=].
您想做类似的事情,但对整个循环使用单个超时通道:
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
}
}