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 關注
- 168 瀏覽
添加回答
舉報