我有以下函数可以派生出一定数量的 go 例程
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
}
我在想 channel 可能有某种方式,但我似乎无法弄清楚。
最佳答案
如果可以使 executePipeline 返回错误,一种方法是使用互斥体:
// ...
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)
}
要使用 channel ,您可以有一个单独的 goroutine 错误列表:
errCh := make(chan error)
go func() {
for e := range errCh {
errs = append(errs, e)
}
}
并在 Execute
函数中,进行以下更改:
// ...
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)
如果 goroutine 的数量不多,你总是可以使用上面列出的 @zerkms 方法。
无需从 executePipleline
返回错误并使用匿名函数包装器,您始终可以在函数本身内进行上述更改。
关于go - 将 go 例程的多个结果聚合到一个数组中,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/45725688/