使用WaitGroup等待goroutine执行完成
go 刘宇帅 6年前 阅读量: 1314
package main
import (
"sync"
"fmt"
"time"
)
func main() {
var wg sync.WaitGroup
ch := make(chan int)
goroutineNum := 2
for i := 0; i < goroutineNum; i ++ {
wg.Add(1)
go doSomeThing(i, ch, &wg)
}
for j := 0; j < goroutineNum; j ++ {
ch<-j
}
close(ch)
wg.Wait()
fmt.Printf("all is done\n")
}
func doSomeThing(goroutineId int, ch chan int, wg *sync.WaitGroup) {
defer wg.Done()
for {
select {
case _ = <-ch:
time.Sleep(2 * time.Second)
fmt.Printf("%v is done\n", goroutineId)
return
}
}
}