Search code examples
gogoroutinebarrier

One barrier for multiple go routines


I am experimenting with go routines.

I have a go routine function executed x times, and I want to wait for all of theses routines to continue in my main function. I've try to use chan for the barrier.

I've try something like that:

func goroutine(i int, ch []chan bool) {
    //do stuff
    ch[i] <- true
}

func main() {
    var ch []chan bool
    for i := 0; i < nb; i++ {
        ch[i] = make(chan bool)
        go goroutine(i, ch)
    }

    // wait to continue
    for i := 0; i < nb; i++ {
         <- ch[i]
    }
}

I have the following error : panic: runtime error: index out of range for the line ch[i] = make(chan bool)

First question:

  • is the good solution to use chan ?

Second question:

  • Why do I have this index out of range error ?

Solution

  • If you just want to wait for the goroutines to complete and don't need to get a result back over the channel, then sync.WaitGroup would be a cleaner solution. The way that would work is:

    • Create a WaitGroup wg and whenever you start a goroutine call wg.Add(1) and pass a pointer to the wg to the goroutine.
    • In the goroutine, before returning call wg.Done()
    • To wait for all the goroutines to finish, call wg.Wait()