Junior
Milleks kasutatakse WaitGroupi Go-s?
sobes.tech AI
Vastus AI-lt
WaitGroup is used to synchronize the work of one or more goroutines. It allows the main goroutine to wait for the completion of other created goroutines. It consists of a counter that increases when a goroutine is created and decreases when it finishes.
Main methods:
Add(delta int): Increases or decreases the goroutine counter.Done(): Decreases the counter by 1. Usually called at the end of a goroutine (often withdefer).Wait(): Blocks execution until the counter reaches zero.
Example usage:
package main
import (
"fmt"
"sync"
)
func worker(id int, wg *sync.WaitGroup) {
defer wg.Done() // Decreases the counter when goroutine finishes
fmt.Printf("Goroutine %d starts\n", id)
// Simulate work
// time.Sleep(time.Second)
fmt.Printf("Goroutine %d ends\n", id)
}
func main() {
var wg sync.WaitGroup // Create a WaitGroup
for i := 1; i <= 5; i++ {
wg.Add(1) // Increment counter for each goroutine
go worker(i, &wg) // Start goroutine, passing pointer to WaitGroup
}
wg.Wait() // Wait until counter is zero (all goroutines finish)
fmt.Println("All goroutines completed")
}