2 回答

TA貢獻(xiàn)1842條經(jīng)驗(yàn) 獲得超22個(gè)贊
查看 ,代碼似乎期望從通道接收四條消息。但是,此代碼最多可以從兩個(gè) goroutine 生成兩個(gè)這樣的消息,因此這是一個(gè)錯(cuò)誤。countdone
此外,如果任何一個(gè) goroutine 返回錯(cuò)誤,它就不會(huì)寫入通道,所以這是另一個(gè)錯(cuò)誤。done
另一種寫法可能是:
...
result := "processed"
for {
select {
case err := <-errc:
close(quit) // Tell the goroutines to terminate
log.Info("event: %s, %s", "", err.Error())
wg.Wait() // Wait for them to finish
return "", err
case <-done:
count++
if count == 2 {
wg.Wait()
return result, nil
}
}

TA貢獻(xiàn)1829條經(jīng)驗(yàn) 獲得超6個(gè)贊
這正是 errgroup 包設(shè)計(jì)用于的分叉和聯(lián)接并發(fā)類型:
func processEvent(ctx context.Context, i models.Foo) (string, error) {
err := func1()
if err != nil {
return "", err
}
g, ctx := errgroup.WithContext(ctx)
if strings.ToUpper(i.Status) != "OK" {
return "", nil
}
g.Go(func() error { return longTimeTask1(ctx) })
g.Go(func() error { return longTimeTask2(ctx) })
if err := g.Wait(); err != nil {
log.Printf("event: %v", err)
return "", err
}
return "processed", nil
}
(https://play.golang.org/p/JNMKftQTLGs)
- 2 回答
- 0 關(guān)注
- 73 瀏覽
添加回答
舉報(bào)