Non-blocking receive with select
suggest changeYou can use default
part of select
statement to do a non-blocking wait.
func main() {
ch := make(chan int, 1)
end:
for {
select {
case n := <-ch:
fmt.Printf("Received %d from a channel\n", n)
break end
default:
fmt.Print("Channel is empty\n")
ch <- 8
}
// wait for channel to be filled with values
// don't use time.Sleep() like that in production code
time.Sleep(20 * time.Millisecond)
}
}
Channel is empty
Received 8 from a channel
During first iteration of for
loop select
immediately ends up in default
clause because channel is empty.
We send a value to the channel there so the next select will pick up the value from the channel.
Found a mistake? Have a question or improvement idea?
Let me know.
Table Of Contents