Reading from multiple channels simultaneously in Golang

前端 未结 3 1552
梦毁少年i
梦毁少年i 2021-01-04 20:46

I am new to Golang. Right now I am trying to figure out how to make an any-to-one channel in Golang, where the setup is as follows:

say I have two goroutines numgen1

3条回答
  •  暖寄归人
    2021-01-04 21:21

    To answer the question "Reading from multiple channels simultaneously"

    There is a way to listen to multiple channels simultaneously :

    func main() {
    
        c1 := make(chan string)
        c2 := make(chan string)
    
        ...
        go func() {
            for {
                select {
                    case msg1 := <- c1:
                    fmt.Println(msg1)
    
                    case msg2 := <- c2:
                    fmt.Println(msg2)
                 }
            }
        }()
    

    In this example, I create a channel msg1 and msg2. Then I create a go routine with an infinite loop. In this loop, I listen to msg1 AND msg2. This system allow you to read to multiple channels simultaneously and to process the messages when the arrive.

    In order to avoid leaks, I should probably add another channel to stop the goroutine.

提交回复
热议问题