Go 如何等待围棋程序完成?
以下是场景:Go 如何等待围棋程序完成?,go,goroutine,Go,Goroutine,以下是场景: 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
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:=g(abc)//返回您可以使用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()
使用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()
var wg sync.WaitGroup
为了{
不管怎样,ok:=如果频道未关闭且为空len()
返回0
如果我知道len(inputCh)
那么我只会启动这么多goroutine,不是吗?如果我知道len(inputCh)
那么我只会启动这么多goroutine,不是吗?@guenhter是的,是的