2 回答

TA贡献1859条经验 获得超6个赞
使用sync.WaitGroup并检查通道何时关闭
var wg sync.WaitGroup
for {
whatever, ok := <-inputCh
if !ok { // check inputCh is close
break
}
// add delta
wg.Add(1)
go func(whatever []string) {
matches := f(xyz, whatever)
m.Lock()
slice = append(slice, matches)
m.Unlock()
// goroutine is done
wg.Done()
}(whatever)
}
// waits until all the goroutines call "wg.Done()"
wg.Wait()

TA贡献1798条经验 获得超3个赞
您可以使用sync.WaitGroup.
// create a work group
var wg sync.WaitGroup
// add delta
wg.Add(len(inputCh))
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()
// signal work group that the routine is done
wg.Done()
}(whatever)
}
// waits until all the go routines call wg.Done()
wg.Wait()
- 2 回答
- 0 关注
- 195 浏览
添加回答
举报