Overview #
Concurrency is a fundamental aspect of modern software development, and the Go programming language excels at handling concurrent tasks efficiently.
One powerful tool in Go's concurrency toolkit is the sync
package, which includes the WaitGroup
type.
Specifically we're going to look at the Add
, Done
and Wait
methods.
Usage #
package main
import (
"fmt"
"sync"
)
func main() {
var wg sync.WaitGroup // create the WaitGroup
for i := 1; i <= 3; i++ {
wg.Add(1) // increase the WaitGroup's counter by 1
go func(id int) {
defer wg.Done() // ensure we decrement the waitgroup's internal counter
// do work here!
}(i)
}
wg.Wait()
}
Common Errors #
A common first mistake can be placing the wg.Add(1)
inside the go func itself.
Unfortunately this results in a race condition, where wg.Wait()
doesn't block as intended, since the the wg.Add(1)
call has not yet been made.