Sobes.tech
Junior

What is WaitGroup used for in Go?

sobes.tech AI

Answer from AI

WaitGroup is used for synchronizing the work of one or more goroutines. It allows the main goroutine to wait for the completion of other goroutines that have been started. It consists of a counter that increases when a goroutine is created and decreases when it finishes.

Main methods:

  • Add(delta int): Increases or decreases the goroutine counter.
  • Done(): Decreases the counter by 1. Usually called at the end of a goroutine (often with defer).
  • Wait(): Blocks execution until the counter becomes zero.

Example usage:

package main

import (
	"fmt"
	"sync"
)

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

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

func main() {
	var wg sync.WaitGroup // Create a WaitGroup

	for i := 1; i <= 5; i++ {
		wg.Add(1) // Increase the counter for each goroutine
		go worker(i, &wg) // Launch goroutine, passing pointer to WaitGroup
	}

	wg.Wait() // Wait until the counter is 0 (all goroutines finish)
	fmt.Println("All goroutines are finished")
}