My code looks like this:
outChannel := make(chan struct{})
...
for out := range outChannel {
...
}
I have a producer writing to outChannel and would like to timeout on reading from it (if overall processing takes more than XX seconds).
What would be the proper way to do so?
As I've only seen construct (at: https://github.com/golang/go/wiki/Timeouts) using select with multiple cases reading from the channels, however, this seems not applicable once using range.
You want to do something similar, but use single timeout channel for the whole loop:
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
}
}
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With