dongwu4834 2017-08-17 02:27
浏览 86

将go例程中的多个结果聚合到单个数组中

I have the following function which spins off a given amount of go routines

func (r *Runner) Execute() {
    var wg sync.WaitGroup
    wg.Add(len(r.pipelines))
    for _, p := range r.pipelines {
        go executePipeline(p, &wg)
    }

    wg.Wait()

    errs := ....//contains list of errors reported by any/all go routines

}

I was thinking there might be some way with channels, but I can't seem to figure it out.

  • 写回答

2条回答 默认 最新

  • dongxiong5546 2017-08-17 05:20
    关注

    One way to do this is using mutexes if you can make executePipeline retuen errors:

    // ...
    for _, p := range r.pipelines {
        go func(p pipelineType) {
            if err := executePipeline(p, &wg); err != nil {
                mu.Lock()
                errs = append(errs, err)
                mu.UnLock()
            }
        }(p)
    }
    

    To use a channel, you can have a separate goroutine listning for errors:

    errCh := make(chan error)
    
    go func() {
        for e := range errCh {
            errs = append(errs, e)
        }
    }
    

    and in the Execute function, make the following changes:

    // ...
    wg.Add(len(r.pipelines))
    for _, p := range r.pipelines {
        go func(p pipelineType) {
            if err := executePipeline(p, &wg); err != nil {
                errCh <- err
            }
        }(p)
    }
    
    wg.Wait()
    close(errCh)
    

    You can always use @zerkms method listed above if the number of goroutines is not high.

    instead of returning error from executePipleline and using a anonymous function wrapper, you can always make above changes within the function itself.

    评论

报告相同问题?

悬赏问题

  • ¥15 如何获取烟草零售终端数据
  • ¥15 数学建模招标中位数问题
  • ¥15 phython路径名过长报错 不知道什么问题
  • ¥15 深度学习中模型转换该怎么实现
  • ¥15 HLs设计手写数字识别程序编译通不过
  • ¥15 Stata外部命令安装问题求帮助!
  • ¥15 从键盘随机输入A-H中的一串字符串,用七段数码管方法进行绘制。提交代码及运行截图。
  • ¥15 TYPCE母转母,插入认方向
  • ¥15 如何用python向钉钉机器人发送可以放大的图片?
  • ¥15 matlab(相关搜索:紧聚焦)