Sobes.tech
Junior

What is a WaitGroup in Go and what is it used for?

sobes.tech AI

Answer from AI

WaitGroup is a synchronization mechanism in Go that allows waiting for a group of goroutines to finish.

Used for:

  • Waiting for all goroutines to complete before exiting a function or program.
  • Coordinating work between multiple goroutines.

Example of usage:

package main

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

func worker(id int, wg *sync.WaitGroup) {
	defer wg.Done() // Decrease the counter upon goroutine completion

	fmt.Printf("Worker %d started\n", id)
	time.Sleep(time.Second) // Simulate work
	fmt.Printf("Worker %d finished\n", id)
}

func main() {
	var wg sync.WaitGroup // Declare WaitGroup
	numWorkers := 3

	for i := 1; i <= numWorkers; i++ {
		wg.Add(1) // Increment counter before starting each goroutine
		go worker(i, &wg)
	}

	wg.Wait() // Block until the counter is zero
	fmt.Println("All workers finished")
}

Main methods:

  • Add(delta int): Increases the internal counter of the WaitGroup by delta. Should be called before starting each goroutine to be tracked.
  • Done(): Decreases the internal counter of the WaitGroup by 1. Usually called in defer inside the goroutine to ensure the counter decreases even if a panic occurs.
  • Wait(): Blocks the current goroutine until the internal counter of the WaitGroup becomes zero.