A channel multiplexer

前端 未结 3 905
梦谈多话
梦谈多话 2020-12-19 14:19

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.<

相关标签:
3条回答
  • 2020-12-19 14:55

    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.

    • Code: https://github.com/eapache/channels
    • Documentation: https://godoc.org/github.com/eapache/channels
    0 讨论(0)
  • 2020-12-19 15:00

    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.

    0 讨论(0)
  • 2020-12-19 15:09

    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() {
        ...
        }()
    }
    
    0 讨论(0)
提交回复
热议问题