1

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.

Jonathan Hall
  • 75,165
  • 16
  • 143
  • 189
bli00
  • 2,215
  • 2
  • 19
  • 46
  • That post is about listening to N channels with select statements. Mine is about simultaneously listening to all the channels at once with the goal of learning they all received a value. – bli00 Mar 07 '19 at 05:30

1 Answers1

4

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()
}
Saurav Prakash
  • 1,880
  • 1
  • 13
  • 24