2017-08-17 10 views
0

に入るルーチンから複数の結果を集約私はチャンネルのいくつかの方法があるかもしれません考えていたが、私はできません単一のアレイ

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 

} 

ゴールーチンの一定量をオフスピン以下の機能を持っていますそれを理解しているようだ。チャネルを使用するには

// ... 
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) 
} 

、あなたがエラーをlistning別のゴルーチンを持つことができます。これを行うには

+0

は 'LEN(r.pipelines)サイズのスライスを作成し'とそれらにすべての労働者の書き込みをしましょう対応するインデックス。 – zerkms

+2

いくつかのチャンネルの結果をFan Inという名前のものに組み合わせるパターンがあります。そのパターンでアプローチを使用することができます(必ずしもパターン自体ではない)。 –

答えて

0

一つの方法は、あなたがexecutePipeline retuenエラーを作ることができれば、ミューテックスを使用している

errCh := make(chan error) 

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

と関数では、次のように変更します。

// ... 
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) 

goroutinesの数が多くない場合、上記の@zerkmsメソッドを常に使用できます。

executePiplelineからエラーを返す代わりに、匿名関数ラッパーを使用すると、関数内で上記の変更を行うことができます。 @Kaveh Shahbazianが提案されているよう

0

あなたはチャンネルを使用することができます。

func (r *Runner) Execute() { 
    pipelineChan := makePipeline(r.pipelines) 

    for cnt := 0; cnt < len(r.pipelines); cnt++{ 
     //recieve from channel 
     p := <- pipelineChan 
     //do something with the result 
    } 
} 

func makePipeline(pipelines []pipelineType) <-chan pipelineType{ 
    pipelineChan := make(chan pipelineType) 

    go func(){ 
     for _, p := range pipelines { 
      go func(p pipelineType){ 
       pipelineChan <- executePipeline(p) 
      }(p) 
     } 
    }() 
    return pipelineChan 
} 

をこの例を参照してください:https://gist.github.com/steven-ferrer/9b2eeac3eed3f7667e8976f399d0b8ad

関連する問題