What are wait groups in Golang?
Wait groups
We can use a WaitGroup to wait for multiple goroutines to finish.
Example
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()}
Explanation
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:
- create a new instance of sync.WaitGroup (in our example, this is
wg) - Call
wg.Add(1), once per Goroutine. It’s perfectly okay to includewg.Addinside a loop programmatically. - Execute defer
wg.Done()in each goroutine to indicate that goroutine is finished executing to the WaitGroup. - Call
wg.Wait()where we want to block.
sync.WaitGroupoffers a simple, yet powerful way to coordinate multiple goroutines in the main driver function.
Free Resources