Go 1.27 reference · Concurrency
Go sync.WaitGroup Type
Wait for a group of goroutines to finish; WaitGroup.Go (Go 1.25+) starts a goroutine and tracks it in one call.
Go 1.27 Since 1.25
Syntax
func (wg *WaitGroup) Go(f func()) func (wg *WaitGroup) Wait()
Parameters
| Parameter | Description |
|---|---|
Go(f) |
Run f in a new goroutine and count it (Go 1.25+). |
Add / Done |
The older manual counting style. |
Wait() |
Block until all are done. |
Examples
package main
import (
"fmt"
"sync"
)
func main() {
var wg sync.WaitGroup
results := make([]int, 4)
for i := range 4 {
wg.Go(func() {
results[i] = i * i
})
}
wg.Wait()
fmt.Println(results)
}
Output
[0 1 4 9]
Run this on your computer — see “Get Started” for setup.
package main
import (
"fmt"
"sync"
)
func main() {
var wg sync.WaitGroup
var mu sync.Mutex
total := 0
for _, n := range []int{5, 10, 15} {
wg.Add(1)
go func() {
defer wg.Done()
mu.Lock()
total += n
mu.Unlock()
}()
}
wg.Wait()
fmt.Println(total)
}
Output
30
Run this on your computer — see “Get Started” for setup.
Version history
| Version | Change |
|---|---|
| Go 1.25 | Added |
Related
sync.Mutex and sync.Once· Protect shared data so only one goroutine accesses it at a time, and run initialisation exactly once.chan, select and close· Send values between goroutines with channels, wait on several with select, and close a channel to end range loops.- Go Goroutines and WaitGroup · tutorial