Sobes.tech
Junior

Kuidas programmeerimiskeeles (Go) puhul tuvastada, et kõik jooksvad goroutinid on lõpetanud ja juhtpõimik saab kasutada tulemusi?

sobes.tech AI

Vastus AI-lt

In Go, the sync.WaitGroup type is commonly used to track the completion of all running goroutines. It allows the main thread to wait until all goroutines have finished execution.

Usage example:

var wg sync.WaitGroup

wg.Add(3) // waiting for 3 goroutines

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

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

This way, WaitGroup allows for synchronization of execution and guarantees that the controlling thread will wait for the completion of all parallel tasks.