WaitGroup example in Go
Introduction
In Go, WaitGroup is a useful feature that allows a program to wait for a group of goroutines to finish executing before continuing. A WaitGroup is used to synchronize the execution of multiple goroutines. In this blog post, we will explore a simple example of WaitGroup in Go.
Simple example
func main() {
var wg sync.WaitGroup
wg.Add(3)
go func(){
defer wg.Done()
doThing1()
}()
go func(){
defer wg.Done()
doThing2()
}()
go func(){
defer wg.Done()
doThing3()
}()
wg.Wait()
}
Real world example
func processAndGather(in <-chan int, processor func(int) int, num int) []int {
out := make(chan int, num)
var wg sync.WaitGroup
wg.Add(num)
for i := 0; i < num; i++ {
go func() {
defer wg.Done()
for v := range in {
out <- processor(v)
}
}()
}
go func() {
wg.Wait()
close(out)
}()
var result []int
for v := range out {
result = append(result, v)
}
return result
}