同时收听Go频道阵列[重复]

This question already has an answer here:

Suppose I have a slice of go receiving channels. Is there a way I can listen to all of them at once? For example:

channels := make([]<-chan int, 0, N)
// fill the slice with channels
for _, channel := range channels {
  <-channel
}

Is the closest I can get to doing that. However, this implementation is dependent on the order of the elements of the slice.

For clarity, I don't need to know the values of the go channel. I just need to know they all finished.

</div>

You can use sync package to create a waitgroup. Start a goroutine for each channel after adding to waitGroup. Finally when channel is done it decrements waitGroup. The caller just waits on waitgroup. Here is the playground link.

package main

import (
    "fmt"
    "sync"
    "time"
)

func main() {
    wg       := sync.WaitGroup{}
    numChans := 10
    chans    := make([]chan interface{}, numChans)

    for i:=0;i<numChans;i++ {
      chans[i] = make(chan interface{})
      wg.Add(1) 
      go func(c chan interface{}) {
        defer wg.Done()     
        <-c 
      }(chans[i])
    }

    //simulate closing channels
    go func(){
       time.Sleep(time.Second)
       fmt.Println("closing")
        for _, ch := range chans{
            close(ch)
        }       
    }()

    fmt.Println("waiting")
    wg.Wait()
}