Use sync.WaitGroup to synchronize goroutines


(This post is a modification edition of Use sync.WaitGroup in Golang).

sync.WaitGroup provides a goroutine synchronization mechanism, and used for waiting for a collection of goroutines to finish. In the internal of sync.WaitGroup struct, there is a counter which records how many goroutines need to be waited are living now.

sync.WaitGroup provides 3 methods: Add, Done and Wait. Add method is used to identify how many goroutines need to be waited, and it will add counter value. When a goroutine exits, it must call Done, and it will decrease counter value by 1. The main goroutine blocks on Wait, once the counter becomes 0, the Wait will return, and main goroutine can continue to run.

Let’s see an example:

  1. package main
  2. import (
  3. "sync"
  4. "time"
  5. "fmt"
  6. )
  7. func sleepFun(sec time.Duration, wg *sync.WaitGroup) {
  8. defer wg.Done()
  9. time.Sleep(sec * time.Second)
  10. fmt.Println("goroutine exit")
  11. }
  12. func main() {
  13. var wg sync.WaitGroup
  14. wg.Add(2)
  15. go sleepFun(1, &wg)
  16. go sleepFun(3, &wg)
  17. wg.Wait()
  18. fmt.Println("Main goroutine exit")
  19. }

Because the main goroutine need to wait 2 goroutines, so the argument for wg.Add is 2. The execution result is like this:

  1. goroutine exit
  2. goroutine exit
  3. Main goroutine exit