Working with WaitGroups in Go

11.26.2021

Intro

When using goroutines, you often need to wait for many goroutines to complete. You can set a timer, but this can be inconsistent as you don't always know how long the goroutines will take. To solve this, we can use WaitGroups. In this article, we will learn how to work with WaitGoups in Go.

Using WaitGroups

Let's start by creating a wait group. We then use the Add method which tells the wait group how many goroutines we will run.

var waitgroup sync.WaitGroup
waitgroup.Add(2)

Next, let's create a function that will be our go routine. This function will take a pointer to our waitgroup. Once the function is finished, it will tell the wait group by calling Done.

func sum(waitgroup *sync.WaitGroup) {
	sum := 0
	for i := 0; i < 10; i++ {
		sum += i
	}
	fmt.Println(sum)
	waitgroup.Done()
}

We then call this function using a go routine and then call Wait on our waitgroup. We call this twice as we told our waitgroup we will have two goroutines.

go sum(&waitgroup)
go sum(&waitgroup)
waitgroup.Wait()

The Full Example

Here is the full example code. You can run this by copying the contents into a file called main.go and then running go run main.go.

package main

import (
	"fmt"
	"sync"
)

func sum(waitgroup *sync.WaitGroup) {
	sum := 0
	for i := 0; i < 10; i++ {
		sum += i
	}
	fmt.Println(sum)
	waitgroup.Done()
}

func main() {
	var waitgroup sync.WaitGroup
	waitgroup.Add(2)

	go sum(&waitgroup)
	go sum(&waitgroup)
	waitgroup.Wait()
}