Member-only story
Use the WaitGroup Wisely in Concurrent Programs in Go
WaitGroup is a synchronization primitive that lets your program know when a set of goroutines have been completed.
In this post, we will explore when and how to use it to synchronize the execution of goroutines.
Start From An Example
The following is a simple example of WaitGroup usage.
- Line # 1: create a WaitGroup variable
- Line #3–#10: define two different functions to run in separate goroutines.
- Line #12: add two goroutines to the WaitGroup.
- Line #14–#15: start the two goroutines.
- Line #17: the main goroutine waits for the two goroutines to finish
- The End

As shown in the example, the WaitGroup is like a concurrent-safe counter that can be incremented and decremented. We call the Add…