Example for sync.WaitGroup correct?

后端 未结 3 826
北荒
北荒 2020-11-28 19:10

Is this example usage of sync.WaitGroup correct? It gives the expected result, but I am unsure about the wg.Add(4) and the position of wg.Don

3条回答
  •  爱一瞬间的悲伤
    2020-11-28 19:46

    • small improvement based on Mroth answer
    • using defer for Done is safer
      func dosomething(millisecs time.Duration, wg *sync.WaitGroup) {
      wg.Add(1)
      go func() {
          defer wg.Done()
          duration := millisecs * time.Millisecond
          time.Sleep(duration)
          fmt.Println("Function in background, duration:", duration)
      }()
    }
    
    func main() {
      var wg sync.WaitGroup
      dosomething(200, &wg)
      dosomething(400, &wg)
      dosomething(150, &wg)
      dosomething(600, &wg)
      wg.Wait()
      fmt.Println("Done")
    }
    

提交回复
热议问题