sync.WaitGroup
- Version
- 1.27
- Review
- Draft
Summary#
A sync.WaitGroup lets one goroutine wait for a batch of tasks to finish. Use Go to start and track a function, then call Wait before reading its results.
Syntax#
var group sync.WaitGroup
group.Go(func() { /* work */ })
group.Wait()
Example#
package main
import (
"fmt"
"sync"
)
func main() {
var group sync.WaitGroup
var words [2]string
group.Go(func() { words[0] = "ready" })
group.Go(func() { words[1] = "set" })
group.Wait()
fmt.Println(words[0], words[1])
}
Expected output#
The goroutines write distinct array elements. The program reads them after both functions finish.
ready set
Common mistakes#
A WaitGroup coordinates completion. Use a mutex or another synchronization mechanism when tasks can mutate the same value. Keep one WaitGroup instance and avoid copying it after first use. Start tasks with Go before waiting on an empty group. With Add and Done, increment before launching the goroutine and call Done once per task.
Version applicability#
The example requires Go 1.25 for WaitGroup.Go. A function passed to Go must return without panicking. From Go 1.0 onward, the equivalent manual pattern is Add(1) before starting each goroutine and defer group.Done() inside it.
Sources#
- Attribution
- DevLookup contributors
- License
- CC-BY-4.0