How to Use sync.WaitGroup in Go

sync.WaitGroup blocks the main goroutine until all launched goroutines call Done() to signal completion.

Use sync.WaitGroup to wait for a collection of goroutines to finish by incrementing the counter before launching them and calling Done() when they complete.

var wg sync.WaitGroup
wg.Add(2)

for i := 0; i < 2; i++ {
    go func(id int) {
        defer wg.Done()
        // do work
    }(i)
}

wg.Wait()