2 ms·
How does go select over N channels where N is not known at compile time these days? I remember the helper API as clumsy and unintuitive. I am sure this has chan
by bjoli 8y ago
How does go select over N channels where N is not known at compile time these days? I remember the helper API as clumsy and unintuitive. I am sure this has changed since I last used go. Back then (about 2014?) I found go's concurrency model lacking, or at least a little bit too opinionated when compared to CML. Sure, it was possible to work around the limitation, and the extra performance you got from utilising all cores was worth it (parallel CML is a rather new thing, but is getting more common.).
- cdoxsey 8y agoHere's one way: func fanin(out chan<- int, ins ...chan int) { switch len(ins) { case 0: case 1: for msg := range ins[0] { out <- msg } case 2: for { var msg int select { case msg = <-ins[0]: case msg = <-ins[1]: } out <- msg } default: go fanin(out, ins[:len(ins)/2]...) go fanin(out, ins[len(ins)/2:]...) } } https://play.golang.org/p/9KNkheXHUBr https://play.golang.org/p/9KNkheXHUBr You can also use reflect: https://golang.org/pkg/reflect/#Select https://golang.org/pkg/reflect/#Select