Sobes.tech
Senior

What is the most popular way to control the completion of all goroutines?

sobes.tech AI

Answer from AI

The most popular way to control the completion of all goroutines in Go is to use sync.WaitGroup. This mechanism allows the main thread to wait for a set of goroutines to finish.

Example usage:

var wg sync.WaitGroup

wg.Add(3) // expecting 3 goroutines

for i := 0; i < 3; i++ {
    go func(id int) {
        defer wg.Done() // signal completion
        // goroutine work
        fmt.Println("Goroutine", id, "finished")
    }(i)
}

wg.Wait() // wait until the counter reaches 0
fmt.Println("All goroutines are finished")

WaitGroup is convenient because it allows you to know exactly when all launched goroutines have finished, without needing to use complex channels or timers.