go waitgroup

package main

import (
	"fmt"
	"sync"
	"time"
)

func process(i int, wg *sync.WaitGroup) {
	fmt.Println("started Goroutine ", i)
	time.Sleep(2 * time.Second)
	fmt.Printf("Goroutine %d ended\n", i)
	wg.Done() // wg-1
}
func main() {
	no := 3
	var wg sync.WaitGroup // 注意sync.WaitGroup是一个结构体, 传参数时注意
	//wg.Wait()
	fmt.Println("wait return")
	fmt.Printf("wait return 你好啊 %d\n", no)
	for i := 0; i < no; i++ {
		wg.Add(1)
		go process(i, &wg) // 传参数是地址
	}
	wg.Wait() //wg相当于一个计数,起一个goroutine时,wg+1当, 结束wg.Done(), wg-1,wg=0时,返回wg.Wait()
	fmt.Println("All go routines finished executing")
}
posted @ 2022-03-10 22:03  ty1539  阅读(25)  评论(0编辑  收藏  举报