golang 多协程执行通过channel收集结果
2021-07-02 本文已影响0人
我爱张智容
package main
import (
"fmt"
"sync"
"time"
)
func job(index int) int {
time.Sleep(time.Millisecond * 500)
//fmt.Println(index)
return index
}
func main() {
start := time.Now()
num := 5
res := make(chan int)
wg := sync.WaitGroup{}
for i := 0; i < num; i++ {
wg.Add(1)
go func(i int) {
defer wg.Done()
res <- job(i)
}(i)
}
//等待所有goroutine执行完之后再关闭通道 defer方式关闭
go func() {
defer close(res)
wg.Wait()
}()
for v := range res {
fmt.Println("v:", v)
}
end := time.Since(start)
fmt.Println(" 耗时 : ", end.String())
}