course/Concurrency/waitgroup.go

41 lines
567 B
Go

package main
import (
"fmt"
"math/rand"
"sync"
"time"
)
//waitGroup
func f() {
//生成随机数
rand.New(rand.NewSource(time.Now().UnixNano()))
for i := 0; i < 5; i++ {
r1 := rand.Int()
r2 := rand.Intn(10)
fmt.Println(r1, r2)
}
}
func f1(i int) {
defer wg.Done() //任务结束后计数器-1
time.Sleep(time.Second * time.Duration(rand.Intn(3)))
fmt.Println(i)
}
var wg sync.WaitGroup
func main() {
for i := 0; i < 10; i++ {
wg.Add(1)
go f1(i)
}
//如何知道这10个goroutine都结束了
wg.Wait() //等待wg的计数器减为0
}