TExcelTAD
Home › Go › Go WaitGroup

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

go · try it yourself
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:

  1. Call Add in the parent goroutine, before the go statement. If you called it inside the goroutine, Wait might run before Add and return too early.
  2. Call Done with defer as the first line of the goroutine, so it happens on every path.
  3. Never copy a WaitGroup after first use. Pass a pointer (*sync.WaitGroup) to functions that need it.

Passing the WaitGroup to a function

go · try it yourself
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.

go · try it yourself
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.

go · try it yourself
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 WaitGroup only tells you that goroutines finished, not whether they succeeded. If the tasks can fail, look at the golang.org/x/sync/errgroup package, which waits and returns the first error.

Test yourself

Where should wg.Add(1) be called?

  1. Inside the goroutine
  2. Before the go statement, in the parent
  3. After wg.Wait()
  4. In a deferred function

What does wg.Wait() do?

  1. Sleeps for one second
  2. Blocks until the counter is zero
  3. Stops all goroutines
  4. Decreases the counter

Why must a WaitGroup be passed as *sync.WaitGroup?

  1. For speed
  2. A copy would have its own counter, so Done would not affect the original
  3. Pointers are required for all structs
  4. It is not required