Note - newbie in Go.
I\'ve written a multiplexer that should merge the outputs of an array of channels into one. Happy with constructive criticism.<
A bit after the fact, I know, but I wrote a package which implements a generic Multiplex function similar to this one. It uses the "select" call in the reflection package to ensure efficient and balanced multiplexing without any need for a lock or wait group.
Each of your goroutines spawned from Mux
ends up pulling from the same channel, since c
gets updated on each iteration of the loop – they don't just capture the value of c
. You will get the expected results if you pass the channel to the goroutine like so:
for _, c := range channels {
go func(c <-chan big.Int) {
...
}(c)
}
You can test this modification here.
One other possible problem is your handling of the n
variable: if you're running with GOMAXPROCS != 1
, you could have two goroutines trying to update it at once. The sync.WaitGroup
type would be a safer way to wait for goroutines to complete.
To build on James Hentridge answer, an idiomatic way to handle the re-assignement problem when using the range
statement is to assign a local variable to the value at stake:
for _, c := range channels {
c := c
go func() {
...
}()
}