方法:
- Add,用来设置WaitGroup的计数值;
- Done,用来将WaitGroup的计数值减1,其实就是调用了Add(-1);
- Wait,调用这个方法的goroutine会一直阻塞,直到WaitGroup的计数值变为0。
案例:
package main
import (
"fmt"
"sync"
)
var wg sync.WaitGroup
func showMSG(i int) {
defer wg.Done() //此处需要defer延迟,保证wg不为0
fmt.Printf("%v\n", i)
}
func main() {
for i := 0; i < 10; i++ {
go showMSG(i)
wg.Add(1)
}
wg.Wait()
fmt.Println("end...")
}