Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

golang timing out reading from channel using range

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.

like image 599
Peter Butkovic Avatar asked Oct 31 '25 04:10

Peter Butkovic


1 Answers

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
    }
}
like image 166
djd Avatar answered Nov 03 '25 02:11

djd



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!