🔥码云GVP开源项目 12k star Uniapp+ElementUI 功能强大 支持多语言、二开方便! 广告
> `WaitGroup`的用途是使得主协程一直阻塞等待直到所有相关的子协程都已经完成了任务后再继续运行 ~~~ package main import ( "fmt" "sync" "time" ) func process(i int, wg *sync.WaitGroup) { fmt.Printf("Goroutine %d started\n", i) time.Sleep(2 * time.Second) fmt.Printf("Goroutine %d ended\n", i) wg.Done() } func main() { var wg sync.WaitGroup for i := 0; i < 3; i++ { wg.Add(1) go process(i, &wg) } wg.Wait() fmt.Println("All go routines finished executing") } ~~~ > 将其改为匿名函数方式 ~~~ package main import ( "fmt" "sync" "time" ) func main() { var wg sync.WaitGroup for i := 0; i < 3; i++ { wg.Add(1) go func(num int) { fmt.Printf("Goroutine %d started\n", num) time.Sleep(2 * time.Second) fmt.Printf("Goroutine %d ended\n", num) wg.Done() }(i) } wg.Wait() fmt.Println("All go routines finished executing") } ~~~