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

Create a free account to save this page, take notes and track your progress. Sign in

Syntax

func (wg *WaitGroup) Go(f func())   func (wg *WaitGroup) Wait()

Parameters

ParameterDescription
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

Example 1
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.

Add and Done, with a mutex
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

VersionChange
Go 1.25Added

Was this page helpful?