I'm learning Golang, and after reading this post on Go's blog, I have the following question.
I start with the following code (from the post):
select {
case <-ch:
// a read from ch has occurred
case <-timeout:
// the read from ch has timed out
}
And based on what A Tour of Go states:
... It chooses one at random if multiple are ready.
As I understand, it is possible to have my result ready and have a timeout at the same time. My question is whether it is worth it (or correct) to double-check for this inside the default case.
Something like the following:
select {
case <-ch:
// a read from ch has occurred
case <-timeout:
// the read from ch has timed out
// So check ch one last time
select {
case <-ch:
// a read from ch has occurred at same time of a timeout,
// so ignore the timeout
default:
// definitive timeout
}
}
If one of the channels is a timeout, odds of your work being done and the timeout firing at exactly the same time are so small they make no sense to consider.
The statement "... It chooses one at random if multiple are ready." is applicable when you actually have a viable reason for this to happen - when you have a select case on multiple job channels that you're processing with a single goroutine, for instance.