Junior — Middle
Kuidas saab määrata, et kõik lapsegorutined on Go programmis lõpetanud töö?
sobes.tech AI
Vastus AI-lt
In Go, synchronization using the sync.WaitGroup type is commonly used to determine the completion of all child goroutines.
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() // blocks until all goroutines have called Done
fmt.Println("All goroutines have completed")
This way, WaitGroup allows the main goroutine to wait for the completion of all child goroutines.