## sync包 1. sync.WaitGroup ### 1.1主要使用 ~~~ var wg sync.WaitGroup wg.Add(1) wg.Done() wg.Wait() ~~~ ### 2.1 使用详情 ~~~ package api import ( "fmt" "github.com/gin-gonic/gin" "sync" "time" ) var wg sync.WaitGroup type IndexController struct { BaseController } func (index IndexController) Index (ctx *gin.Context) { wg.Add(1) //2 协程添加标记 go channel() // 1 开启一个协程 wg.Add(1) go channel2() data := make(map[string]interface{}) data["msg"] = "success" wg.Wait() //4 等待子协程执行完成 index.successMsg(ctx,data,"") } func channel() { for i := 0;i<5;i++ { time.Sleep(time.Millisecond*1000) fmt.Println(i) } wg.Done()// 3 协程执行完成 } func channel2() { for i := 0;i<5;i++ { time.Sleep(time.Millisecond*1000) fmt.Println(i) } wg.Done()// 3 协程执行完成 } ~~~ 3 捕捉协程中的错误 ``` defer func(){ if err := recover(); err != nil{ fmt.Println("捕捉到了异常",err) } } ``` ![](https://img.kancloud.cn/23/32/2332f6eca96390fa3348f783f499e38f_665x386.png)