Peter Butkovic
Peter Butkovic

Reputation: 12139

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.

Upvotes: 4

Views: 1684

Answers (1)

djd
djd

Reputation: 5178

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
    }
}

Upvotes: 6

Related Questions