On Thu, Apr 29, 2021 at 12:05 PM Øyvind Teig <oyvind.t...@teigfam.net> wrote: > > The example here is a server with N clients where it is essential that none > of clients will starve and none jam the server. I have needed to do this > coding several times. Go has random select which in theory may mean starving > and jamming. I worked with safety critical fire detection, and it was > necessary to ensure this. Or at least we didn't dare to take the chance. We > could not just add another machine. > > To use select when that's fair enough (pun 1) - "fair enough" (pun 2). But If > I want to be certain of no starving or jamming I need to code the fairness > algorithm. I can then promise a client that may have been ready but wasn't > served to come in before I take the previous clients that were allowed. This > is at best very difficult if all we have is select. Having pri select as the > starting point is, in this case, easier.
When there are multiple ready results, the select statement in Go is guaranteed to use a uniform pseudo-random selection (https://golang.org/ref/spec#Select_statements). The fact that cases are selected using a uniform distribution ensures that executing a select statement in a loop can't lead to starving (I'm not sure what jamming is). As several people have said, it's meaningless to say "I want to ensure that if both case A and case B are available then the select statement will choose case A." It's meaningless because it relies on a notion of simultaneity that literally doesn't exist. There will always be a period of time after the select statement chooses B, but before it actually executes the case, that case A may become ready. That will be true for any possible implementation of select, because select is not an atomic operation. Therefore, this code using a hypothetical priority case select { case pri <-c1: case <-c2: } can always be rewritten as select { case <-c1: default: select { case <-c1: case <-c2: } } The rewritten select is exactly equivalent to the first. The only way that they could not be equivalent would be if select were atomic. Ian -- You received this message because you are subscribed to the Google Groups "golang-nuts" group. To unsubscribe from this group and stop receiving emails from it, send an email to golang-nuts+unsubscr...@googlegroups.com. To view this discussion on the web visit https://groups.google.com/d/msgid/golang-nuts/CAOyqgcWZ5eVbjYFksEUQNb1WcXy9uR8ccfBzJP3XsDYLdiUBVw%40mail.gmail.com.