多协程执行后使用channel收集结果--优雅版本
> 由于上个版本由于关闭channel太low了,这是给到优雅版本 仅供参考
func job(index int) int {
time.Sleep(time.Millisecond*500)
return index
}
func main() {
num:=5
result:=make(chan int)
wg:=sync.WaitGroup{}
for i:=0;i<num;i++{
wg.Add(1)
go func(index int) {
defer wg.Done()
result<-job(index)
}(i)
}
go func() {
defer close(result)
wg.Wait()
}()
for item:=range result{
fmt.Println(item)
}
}
本作品采用《CC 协议》,转载必须注明作者和本文链接
推荐文章: