In Rob Pike's Google IO talk on Go Concurrency Patterns, he presented this code as an example of how to pick the fastest responder from a number of replica servers:
func First(query string, replicas ...Search) Result {
c := make(chan Result)
searchReplica := func(i int) { c <- replicas[i](query) }
for i := range replicas {
go searchReplica(i)
}
return <-c
}
Question: Won't this leave N-1 of the replica goroutines blocking on a channel write?
In the discussion after the talk, one of the audience members seems to be asking this question, but got kind of a handy-wavy response.
I'd be inclined to change the 3rd line to something like this:
searchReplica := func(i int) {
select {
case c <- replicas[i](query):
default: // non-blocking write
}
}
You are correct. But that doesn't fit on a single slide. He was talking about concurrency patterns, not necessarily the code to do it.
Of course, I still wouldn't have put that code on a slide...