WaitGroup
Learn about WaitGroup in the sync package.
We'll cover the following...
Overview of WaitGroup
In lots of previous code, we have encountered the following code lines:
wg.Add()
Or
wg.Wait()
Or
wg.Done()
What exactly do these lines mean? The wg
is a variable-holding instance for sync.WaitGroup
. Use WaitGroup
to wait for all the launched goroutines.
var wg sync.WaitGroup
Requirement of WaitGroup
In order to understand the need for WaitGroup
, let’s walk through some simple code.
Press + to interact
package mainimport ("fmt")func main() {go func() {fmt.Println("I am goroutine 1")}()go func() {fmt.Println("I am goroutine 2")}()}
The code above won’t print anything, but why is that? Let’s see what’s happening behind the scenes to understand this.
The moment the Go compiler starts executing the main.go file, it encounters the main
goroutine (primary function). The compiler then launches the other two anonymous goroutines as well. Since ...