Sobes.tech
Junior

How to track in the Go programming language that all running goroutines have finished and the managing goroutine can use the results?

sobes.tech AI

Answer from AI

In Go, to track the completion of all launched goroutines, the sync.WaitGroup type is usually used. It allows the main thread to wait until all goroutines finish execution.

Example of 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 goroutine completion
        // goroutine work
        fmt.Println("Goroutine", id, "completed")
    }(i)
}

wg.Wait() // main thread blocks until wg counter becomes 0
fmt.Println("All goroutines completed, results can be used")

Thus, WaitGroup allows synchronization of execution and guarantees that the controlling thread will wait for all parallel tasks to complete.