dpziir0079 2018-04-26 21:20
浏览 21
已采纳

多次执行例程的一个障碍

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 ?
  • 写回答

1条回答 默认 最新

  • drix47193 2018-04-26 21:36
    关注

    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()
    本回答被题主选为最佳回答 , 对您是否有帮助呢?
    评论

报告相同问题?

悬赏问题

  • ¥15 装 pytorch 的时候出了好多问题,遇到这种情况怎么处理?
  • ¥20 IOS游览器某宝手机网页版自动立即购买JavaScript脚本
  • ¥15 手机接入宽带网线,如何释放宽带全部速度
  • ¥30 关于#r语言#的问题:如何对R语言中mfgarch包中构建的garch-midas模型进行样本内长期波动率预测和样本外长期波动率预测
  • ¥15 ETLCloud 处理json多层级问题
  • ¥15 matlab中使用gurobi时报错
  • ¥15 这个主板怎么能扩出一两个sata口
  • ¥15 不是,这到底错哪儿了😭
  • ¥15 2020长安杯与连接网探
  • ¥15 关于#matlab#的问题:在模糊控制器中选出线路信息,在simulink中根据线路信息生成速度时间目标曲线(初速度为20m/s,15秒后减为0的速度时间图像)我想问线路信息是什么