Syntax
A sync.WaitGroup waits for a group of goroutines to finish.
var wg sync.WaitGroup
wg.Add(2)
go func() {
// Do work
wg.Done()
}()
go func() {
// Do work
wg.Done()
}()
wg.Wait()
- First the main goroutine calls
Addto set the number of goroutines to wait for. - Then two new goroutines run and call
Donewhen finished.
At the same time, Wait is used to block until these two goroutines have finished.
Note: A WaitGroup must not be copied after first use.
Example - Play with 1 WaitGroup
func main() {
var waitGroup sync.WaitGroup
waitGroup.Add(1) // 1 because we will be executing 1 goroutine
go func() { // Goroutine
printStrFiveTimes("नमस्ते किंशुक") // Call our func inside goroutine
// Below line will decrement the counter in waitGroup
waitGroup.Done() // Notify waitGroup that our func is done executing
}()
waitGroup.Wait() // Wait for goroutines to finish their execution
}
func printStrFiveTimes(str string) {
for i := 1; i <= 5; i++ {
fmt.Printf("%2v %v\n", i, str)
time.Sleep(time.Millisecond * 500)
}
}
Output:
1 नमस्ते किंशुक
2 नमस्ते किंशुक
3 नमस्ते किंशुक
4 नमस्ते किंशुक
5 नमस्ते किंशुक