Skip to Content
Skip to content
Run Concurrent Tasks Safely With sync.WaitGroup and wg.Go
Intermediate
Tutorials

Run Concurrent Tasks Safely With sync.WaitGroup and wg.Go

Wait for parallel goroutines using sync.WaitGroup and wg.Go, collect results into disjoint slice indices without locks, and verify with go test -race. After this, concurrent fan-out runs without data races.

Updated 4 min read GoProgramming Patterns

Launching goroutines with go work(item) is trivial; waiting for every goroutine to finish cleanly and collecting their results without a data race is where subtle production bugs hide. Sleeping with time.Sleep flakes whenever a server slows down, and appending to one shared slice from 10 goroutines corrupts memory under load.

sync.WaitGroup coordinates completion deterministically, and pairing it with pre-allocated slice indices collects results in order with zero locks. Verified on Go 1.27 with -race.

Case 1: Real example—probing multiple service URLs concurrently

Suppose your dashboard checks the HTTP status of several microservices concurrently and needs the results in the exact order the URLs were listed. Notice the two strict ordering rules: wg.Add(1) runs before go func(), and defer wg.Done() runs as the first line inside each goroutine:

package main

import (
	"fmt"
	"net/http"
	"net/http/httptest"
	"sync"
)

type Probe struct {
	URL    string
	Status int
	Err    error
}

func probeAll(client *http.Client, urls []string) []Probe {
	results := make([]Probe, len(urls))
	var wg sync.WaitGroup

	for i, u := range urls {
		wg.Add(1)
		go func() {
			defer wg.Done()
			resp, err := client.Get(u)
			if err != nil {
				results[i] = Probe{URL: u, Err: err}
				return
			}
			resp.Body.Close()
			results[i] = Probe{URL: u, Status: resp.StatusCode}
		}()
	}

	wg.Wait()
	return results
}

func main() {
	s1 := httptest.NewServer(http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) { w.WriteHeader(200) }))
	defer s1.Close()
	s2 := httptest.NewServer(http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) { w.WriteHeader(503) }))
	defer s2.Close()

	out := probeAll(s1.Client(), []string{s1.URL, s2.URL, s1.URL})
	for i, p := range out {
		fmt.Printf("idx=%d status=%d err=%v\n", i, p.Status, p.Err)
	}
}
$ go run -race .
idx=0 status=200 err=<nil>
idx=1 status=503 err=<nil>
idx=2 status=200 err=<nil>

Case 2: Why results[i] is race-free while append fails under -race

If 10 goroutines all execute results = append(results, probe) simultaneously, they concurrently read and overwrite the same slice header (pointer, length, capacity)—triggering WARNING: DATA RACE and silently losing elements. When you pre-allocate make([]Probe, len(urls)), every goroutine i owns its own separate element results[i] in memory, and wg.Wait() establishes a happens-before memory barrier before probeAll returns results.

Case 3: Two classic WaitGroup bugs that hang or drop work

  • Calling wg.Add(1) inside the goroutine: The parent loop can reach wg.Wait() before the scheduler starts the goroutines, seeing count 0 and returning empty results!
  • Passing wg sync.WaitGroup by value to a helper function: Copies the internal counter—so wg.Done() decrements the throwaway copy while the caller hangs forever on wg.Wait()! Always pass *sync.WaitGroup.

Case 4: Go 1.25's wg.Go and when to switch to errgroup

In Go 1.25+, wg.Go(func() { ... }) handles Add(1), go, and defer Done() in a single call:

var wg sync.WaitGroup
for i, u := range urls {
	wg.Go(func() {
		results[i] = probeOne(client, u)
	})
}
wg.Wait()

And if your list has 10,000 URLs—or you want the first error to cancel sibling requests immediately—switch to errgroup.WithContext(ctx) with g.SetLimit(16) from golang.org/x/sync/errgroup so you never open 10,000 sockets at once.

💡 Tip

Run go test -race ./... in CI. Go's race detector instruments shared memory accesses at runtime and immediately catches unsynchronized slice appends or map writes across goroutines.

Common mistakes

  • Passing sync.WaitGroup by value: Always pass a pointer (*sync.WaitGroup) if a helper calls Done().
  • Omitting defer on wg.Done(): An early error return or panic skips a bare wg.Done() at the bottom of the function, hanging wg.Wait() forever.
  • Spawning an unbounded WaitGroup over 50,000 items: Cap concurrency with a fixed worker pool or errgroup.SetLimit.

⚠ Warning

Never reuse a sync.WaitGroup for a second batch of Add calls until the previous wg.Wait() has returned—concurrent Add and Wait panics with sync: WaitGroup is reused before previous Wait has returned.

What happens if you skip this

Concurrent code without strict WaitGroup ownership and race-free result collection passes most local runs, then randomly returns missing items, hangs forever, or crashes under production traffic.

Related course: Go Intermediate.

About

Wait for parallel goroutines using sync.WaitGroup and wg.Go, collect results into disjoint slice indices without locks, and verify with go test -race. After this, concurrent fan-out runs without data races.

Responsible
Jay P
Last Update
11/27/2026
Reading Time
4 min
Was this helpful?
​ 0 ​ 0

Comments

Sign in to comment

No comments yet.