Is it possible to multiplex several channels into one?

后端 未结 3 1862
北海茫月
北海茫月 2021-02-14 00:29

The idea is to have a variable number of channels in a slice, push each value received through them into a single channel, and close this output channel once the last one of the

3条回答
  •  别跟我提以往
    2021-02-14 01:17

    Using goroutines I produced this. Is it what you want ?

    package main
    
    import (
        "fmt"
    )
    
    func multiplex(cin []chan int, cout chan int) {
        n := len(cin)
        for _, ch := range cin {
            go func(src chan int) {
                for {
                    v, ok := <-src
                    if ok {
                        cout <- v
                    } else {
                        n-- // a little dangerous. Maybe use a channel to avoid missed decrements
                        if n == 0 {
                            close(cout)
                        }
                        break
                    }
                }
            }(ch)
        }
    }
    
    // a main to test the multiplex
    func main() {
        cin := make([]chan int, 3)
        cin[0] = make(chan int, 2)
        cin[1] = make(chan int, 2)
        cin[2] = make(chan int, 2)
        cout := make(chan int, 2)
        multiplex(cin, cout)
        cin[1] <- 1
        cin[0] <- 2
        cin[2] <- 3
        cin[1] <- 4
        cin[0] <- 5
        close(cin[1])
        close(cin[0])
        close(cin[2])
        for {
            v, ok := <-cout
            if ok {
                fmt.Println(v)
            } else {
                break
            }
        }
    }
    

    EDIT : References :

    http://golang.org/ref/spec#Receive_operator

    http://golang.org/ref/spec#Close

提交回复
热议问题