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)
   }
}

  

转载于:https://www.cnblogs.com/waken-captain/p/10496626.html

你可能感兴趣的:(goroutine 通过waitgroup 确保 goroutine执行完成,select+time.After+chanel 终止goroutine等待...)