A WaitGroup is a type in Go’s standard library that allows multiple goroutines to wait for a set of operations to complete. It’s used to wait for a collection of Goroutines to finish.
Here’s an example of using a WaitGroup:
package main
import (
"fmt"
"sync"
)
func worker(id int, wg *sync.WaitGroup) {
defer wg.Done()
fmt.Printf("worker %d starting\n", id)
// perform work here
fmt.Printf("worker %d done\n", id)
}
func main() {
var wg sync.WaitGroup
for i := 1; i <= 5; i++ {
wg.Add(1)
go worker(i, &wg)
}
wg.Wait()
fmt.Println("All workers done")
}
In this example, 5 worker goroutines are started and the WaitGroup wg
is used to wait for all of them to complete. The Add
method is used to add the number of Goroutines to wait for. The Done
method is used to decrement the wait group count when a Goroutine finishes. The Wait
method blocks until the count of the WaitGroup goes back to zero.
Leave a Reply