Senior
Kas otsustasid kirjutada WaitGroup, sest kanal ilmus või otsustasid kirjutada goroutines millegi jaoks?
sobes.tech AI
Vastus AI-lt
In Go, WaitGroup is used to wait for a collection of goroutines to finish.
If you have multiple goroutines performing parallel tasks and you need to wait for all of them to complete before proceeding, WaitGroup is a handy tool.
Channels and goroutines are different mechanisms. A channel is used for communication and synchronization between goroutines, while WaitGroup is used to wait for their completion.
For example, if you have goroutines performing tasks and want to wait until all are finished, you use WaitGroup:
var wg sync.WaitGroup
wg.Add(3) // waiting for 3 goroutines
for i := 0; i < 3; i++ {
go func(id int) {
defer wg.Done()
// goroutine work
fmt.Println("Goroutine", id, "done")
}(i)
}
wg.Wait() // wait for all goroutines to finish
This way, WaitGroup is used precisely because there are goroutines that need to be synchronized at their completion, not because channels have appeared.