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)
   }
}
相關文章
相關標籤/搜索