Sobes.tech
Junior — Middle

How can it be determined that all child goroutines have finished executing in a Go program?

sobes.tech AI

Answer from AI

In Go, to determine the completion of all child goroutines, synchronization is usually done using the sync.WaitGroup type.

Example:

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, "completed")
    }(i)
}

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

Thus, WaitGroup allows the main goroutine to wait for the completion of all child goroutines.