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:
Second question:
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:
wg.Add(1)
and pass a pointer to the wg to the goroutine.wg.Done()
wg.Wait()