如何等待 go-routines 完成?

下面是场景:


inputCh := g(abc) // return <- chan []string



slice := make([]map[string][]string, 0)

m := sync.Mutex{}

for whatever := range inputCh {

    go func(whatever []string) {

        matches := f(xyz, whatever) // returns map[string][]string

        m.Lock()

        slice = append(slice, matches)

        m.Unlock()

    }(whatever)

}


z := merge(slice...)

我们不知道的地方,何时inputCh关闭(close(inputCh))


merge(slice...)我们只需要在所有 go-routines 完成和更新后调用slice


不确定,如果sync.WaitGroup可以使用。


如何确保只有在所有 go-routines 更新merge(slice...)后才被调用?slice


陪伴而非守候
浏览 196回答 2
2回答

慕丝7291255

使用sync.WaitGroup并检查通道何时关闭var wg sync.WaitGroupfor {&nbsp; &nbsp; whatever, ok := <-inputCh&nbsp; &nbsp; if !ok { // check inputCh is close&nbsp; &nbsp; &nbsp; &nbsp; break&nbsp; &nbsp; }&nbsp; &nbsp; // add delta&nbsp; &nbsp; wg.Add(1)&nbsp; &nbsp; go func(whatever []string) {&nbsp; &nbsp; &nbsp; &nbsp; matches := f(xyz, whatever)&nbsp; &nbsp; &nbsp; &nbsp; m.Lock()&nbsp; &nbsp; &nbsp; &nbsp; slice = append(slice, matches)&nbsp; &nbsp; &nbsp; &nbsp; m.Unlock()&nbsp; &nbsp; &nbsp; &nbsp; // goroutine is done&nbsp; &nbsp; &nbsp; &nbsp; wg.Done()&nbsp; &nbsp; }(whatever)}// waits until all the goroutines call "wg.Done()"wg.Wait()

呼如林

您可以使用sync.WaitGroup.// create a work groupvar wg sync.WaitGroup// add deltawg.Add(len(inputCh))slice := make([]map[string][]string, 0)m := sync.Mutex{}for whatever := range inputCh {&nbsp; &nbsp; go func(whatever []string) {&nbsp; &nbsp; &nbsp; &nbsp; matches := f(xyz, whatever) // returns map[string][]string&nbsp; &nbsp; &nbsp; &nbsp; m.Lock()&nbsp; &nbsp; &nbsp; &nbsp; slice = append(slice, matches)&nbsp; &nbsp; &nbsp; &nbsp; m.Unlock()&nbsp; &nbsp; &nbsp; &nbsp; // signal work group that the routine is done&nbsp; &nbsp; &nbsp; &nbsp; wg.Done()&nbsp; &nbsp; }(whatever)}// waits until all the go routines call wg.Done()wg.Wait()
打开App,查看更多内容
随时随地看视频慕课网APP

相关分类

Go