Go WaitGroup
When you start several goroutines, you usually need to wait until all of them are finished before you continue — before printing results, closing a channel or returning from main. The sync.WaitGroup type is built exactly for that. It is a counter of outstanding work:
| Method | Effect |
|---|---|
wg.Add(n) |
increase the counter by n (call it before starting the goroutine) |
wg.Done() |
decrease the counter by one (call it when a goroutine finishes, usually with defer) |
wg.Wait() |
block until the counter reaches zero |
wg.Go(f) |
Go 1.25+: Add(1), start f in a goroutine, and call Done when it returns |
The classic pattern
package main
import (
"fmt"
"sync"
)
func main() {
files := []string{"a.txt", "b.txt", "c.txt"}
sizes := make([]int, len(files))
var wg sync.WaitGroup
for i, name := range files {
wg.Add(1) // one more goroutine to wait for
go func() {
defer wg.Done() // always runs, even if the code below returns early
sizes[i] = len(name) * 100 // pretend we measured the file
}()
}
wg.Wait() // blocks here until all three called Done
fmt.Println("all done:", sizes)
}all done: [500 500 500]
Three rules make this pattern correct:
- Call
Addin the parent goroutine, before thegostatement. If you called it inside the goroutine,Waitmight run beforeAddand return too early. - Call
Donewithdeferas the first line of the goroutine, so it happens on every path. - Never copy a
WaitGroupafter first use. Pass a pointer (*sync.WaitGroup) to functions that need it.
Passing the WaitGroup to a function
package main
import (
"fmt"
"sync"
)
func checkSite(url string, wg *sync.WaitGroup, status []string, slot int) {
defer wg.Done()
// A real program would make an HTTP request here.
if len(url) > 15 {
status[slot] = url + " -> slow"
} else {
status[slot] = url + " -> ok"
}
}
func main() {
sites := []string{"go.dev", "example.com", "very-long-domain.org"}
status := make([]string, len(sites))
var wg sync.WaitGroup
wg.Add(len(sites)) // we know the count up front
for i, s := range sites {
go checkSite(s, &wg, status, i)
}
wg.Wait()
for _, line := range status {
fmt.Println(line)
}
}go.dev -> ok
example.com -> ok
very-long-domain.org -> slow
Note the &wg: passing wg by value would copy it, and the goroutines would call Done on their own copies — Wait would then block forever.
The shortcut: wg.Go (Go 1.25)
Go 1.25 added WaitGroup.Go, which combines Add(1), the go statement and defer Done() in one call. It removes the most common mistakes.
package main
import (
"fmt"
"sync"
)
func main() {
inputs := []int{3, 4, 5, 6}
squares := make([]int, len(inputs))
var wg sync.WaitGroup
for i, n := range inputs {
wg.Go(func() {
squares[i] = n * n
})
}
wg.Wait()
fmt.Println(squares)
}[9 16 25 36]
Collecting results through a channel
Another common shape: workers send results to a channel, and a separate goroutine closes the channel once the WaitGroup reaches zero. The main goroutine ranges over the channel. Since results arrive in random order, sort them (or sum them) before printing.
package main
import (
"fmt"
"slices"
"sync"
)
func main() {
words := []string{"kiwi", "banana", "fig", "cherry"}
lengths := make(chan string)
var wg sync.WaitGroup
for _, w := range words {
wg.Go(func() {
lengths <- fmt.Sprintf("%s=%d", w, len(w))
})
}
go func() {
wg.Wait() // when every sender is finished...
close(lengths) // ...close the channel so the range loop ends
}()
var results []string
for r := range lengths {
results = append(results, r)
}
slices.Sort(results)
fmt.Println(results)
}[banana=6 cherry=6 fig=3 kiwi=4]
Common mistakes
| Mistake | Symptom | Fix |
|---|---|---|
Add inside the goroutine |
Wait returns too early, missing results |
call Add before go |
Forgetting Done |
fatal error: all goroutines are asleep - deadlock! |
defer wg.Done() first thing |
Passing wg by value |
deadlock | pass &wg |
More Done calls than Add |
panic: sync: negative WaitGroup counter |
keep counts balanced, or use wg.Go |
Tip: A
WaitGrouponly tells you that goroutines finished, not whether they succeeded. If the tasks can fail, look at thegolang.org/x/sync/errgrouppackage, which waits and returns the first error.
Test yourself
Where should wg.Add(1) be called?
- Inside the goroutine
- Before the
gostatement, in the parent - After
wg.Wait() - In a deferred function
What does wg.Wait() do?
- Sleeps for one second
- Blocks until the counter is zero
- Stops all goroutines
- Decreases the counter
Why must a WaitGroup be passed as *sync.WaitGroup?
- For speed
- A copy would have its own counter, so
Donewould not affect the original - Pointers are required for all structs
- It is not required