goroutine 通过waitgroup 确保 goroutine执行完成,select+time.After+chanel 终止goroutine等待

package main

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

func main() {
   tasks := make(chan bool, 1)
   go func(t chan bool){
      var wg sync.WaitGroup
      // 需要确保3个协程完成
      for i := 1; i <= 3; i++ {
         wg.Add(1)
         go func(ii int) {
            defer panicRecover()
            if err := testa(ii); err != nil {
               t <- false
            }
            wg.Done()
         }(i)
      }
      wg.Wait()
      t <- true
   }(tasks)


   // 限时120s等待协程完毕
   select {
   case <-time.After(time.Second * 120):
      fmt.Println("处理超时")
   case flag := <-tasks:
      if !flag {
         fmt.Println("多协程任务中有失败的")
      }else {
         log.Println("协程正确完成任务")
      }
   }
   fmt.Printf("over")
}


func testa(i int) error {
   time.Sleep(time.Second * 3)
   fmt.Println(i)
   if i == 3 {
      return fmt.Errorf("i can't be 3")
   }
   return nil
}

func panicRecover(){
   if err := recover(); err != nil {
      log.Printf("recover from panic: %v", err)
   }
}

  

posted @ 2019-03-08 16:29  瓦肯船长  阅读(468)  评论(0编辑  收藏  举报