Sobes.tech
Senior

Why do you add a WaitGroup?

sobes.tech AI

Answer from AI

WaitGroup in Go is used for synchronizing multiple goroutines. Its main purpose is to wait for a set of goroutines to finish before continuing the execution of the main program.

When you launch multiple goroutines, to ensure that all of them have completed, you add the number of expected goroutines to the WaitGroup using Add(n). Each goroutine calls Done() upon completion, decreasing the counter. The main goroutine calls Wait(), which blocks until the counter reaches zero.

Example:

var wg sync.WaitGroup

wg.Add(3) // expecting 3 goroutines

for i := 0; i < 3; i++ {
    go func(id int) {
        defer wg.Done()
        fmt.Println("Goroutine", id, "completed")
    }(i)
}

wg.Wait() // wait until all goroutines call Done
fmt.Println("All goroutines completed")

Thus, WaitGroup helps prevent premature termination of the program and ensures that all parallel tasks are completed.

Why do you add a WaitGroup? — Golang - sobes.tech