How to Use Sync.WaitGroup to Wait Goroutines in Go?

How to wait goroutines?
  1. var wg sync.WaitGroup : declare new WaitGroup
  2. wg.Add() : increase counter when there are new goroutine
  3. wg.Done() : decrease counter after the goroutine is done
  4. wg.Wait() : block this goroutine until the counter reset to zero.
  1. You can pass value to routines by using the arguments of the function.
  2. You can use defer defers the execution of a function until the surrounding function returns. i.e., execute code after the function is done.
  3. You can try to omit wg.Wait() and see what will happen?
func main() {
var wg sync.WaitGroup
for i := 0; i < 10; i++ {
go func(j int) {
defer wg.Done()
time.Sleep(time.Duration(rand.Int63n(1000)) * time.Millisecond)
fmt.Println("Routine", j, "is done.")
fmt.Println("Main routine is blocked")
// wg.Wait()
fmt.Println("Main routine is done")



Get the Medium app

A button that says 'Download on the App Store', and if clicked it will lead you to the iOS App store
A button that says 'Get it on, Google Play', and if clicked it will lead you to the Google Play store


A person who loves computer science shares implementations. Github: @liao2000