Skip to content

How to Use WaitGroups in Golang

Initiate a new wait group variable:

var wg sync.WaitGroup

Add how many goroutines you want to wait for:

wg.Add(1) 

In each goroutine call the Done() function at the end of its task:

wg.Done()

Call Wait() at the place you want to wait for all the goroutines to complete:

wg.Wait()

And this is a complete example:

package main

import (
	"fmt"
	"sync"
	"time"
)

func main() {

	var wg sync.WaitGroup

	// Add one to wait group
	wg.Add(2)

	go func() {
		fmt.Println("Hi! I am in a goroutine!")
		fmt.Println("Waiting for 1 seconds ...")

		time.Sleep(1 * time.Second)

		wg.Done()
	}()

	go func() {
		fmt.Println("Hi! I am in a goroutine!")
		fmt.Println("Waiting for 2 seconds ...")

		time.Sleep(2 * time.Second)

		wg.Done()
	}()

	wg.Wait()
}

Leave a Reply

Your email address will not be published. Required fields are marked *