Trusted answers to developer questions

What are wait groups in Golang?

Get Started With Machine Learning

Learn the fundamentals of Machine Learning with this free course. Future-proof your career by adding ML skills to your toolkit — or prepare to land a job in AI or Data Science.

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 main
import (
"fmt"
"sync"
)
var wg sync.WaitGroup
func 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:

  1. create a new instance of sync.WaitGroup (in our example, this is wg)
  2. Call wg.Add(1), once per Goroutine. It’s perfectly okay to include wg.Add inside a loop programmatically.
  3. Execute defer wg.Done() in each goroutine to indicate that goroutine is finished executing to the WaitGroup.
  4. Call wg.Wait() where we want to block.

sync.WaitGroup offers a simple, yet powerful way to coordinate multiple goroutines in the main driver function.

RELATED TAGS

golang
wait

CONTRIBUTOR

Jeyabalaji Subramanian
Copyright ©2024 Educative, Inc. All rights reserved
Did you find this helpful?