We can use a WaitGroup to wait for multiple goroutines to finish.
Before delving into WaitGroup, let’s run the code below and observe the result.
package mainimport ("fmt""sync")var wg sync.WaitGroupfunc hello() {defer wg.Done()fmt.Println("hello from a goroutine!")}func main() {wg.Add(1)go hello()wg.Wait()}
Now, the code will have printed the statement “hello from a goroutine!” correctly!
Let’s look at what WaitGroup does next. From the docs:
A WaitGroup waits for a collection of goroutines to finish. The main goroutine calls Add to set the number of goroutines to wait for. Then, each of the goroutines runs and calls Done when finished. At the same time, Wait can be used to block until all goroutines have finished.
So, in the above code, we used WaitGroup to notify that we are spawning a Goroutine and waiting for it to finish.
The Goroutine that’s called takes the responsibility to signal that the work is done.
To use sync.WaitGroup, we should do the following:
wg
)wg.Add(1)
, once per Goroutine. It’s perfectly okay to include wg.Add
inside a loop programmatically.wg.Done()
in each goroutine to indicate that goroutine is finished executing to the WaitGroup.wg.Wait()
where we want to block.
sync.WaitGroup
offers a simple, yet powerful way to coordinate multiple goroutines in the main driver function.
Free Resources