WaitGroup Reuse Across Batch Phases

Run sequential batches of goroutines with one WaitGroup: after each Wait the counter is back at zero, so the same group serves the next phase.

GoResilience

Code

gosnippet
35 lines
package main

import (
	"fmt"
	"sync"
)

func main() {
	pages := [][]string{
		{"alpha", "beta"},
		{"gamma", "delta", "epsilon"},
		{"zeta"},
	}

	var wg sync.WaitGroup
	results := make([][]string, len(pages))

	for batch, page := range pages {
		// 上一批 Wait 已返回、计数归零后,同一 WaitGroup 可以安全复用
		results[batch] = make([]string, len(page))
		for i, name := range page {
			wg.Add(1)
			go func(batch, i int, name string) {
				defer wg.Done()
				results[batch][i] = "done:" + name
			}(batch, i, name)
		}
		wg.Wait()
		fmt.Println("batch", batch, "complete")
	}

	for batch, rows := range results {
		fmt.Println(batch, rows)
	}
}

Execution shape

Read it this way: the function main, doing all the work.

The loop for batch, page := range pages is the only repeated construct. Work is dispatched on a goroutine. The cleanup call is deferred to function exit — success, early return, and panic all covered.

What to watch for

  • The runtime alone is required — nothing to fetch, nothing to install.

Applying it

The entry-point signature is func main()

The file’s steps show up in the output as batch.

Statements that matter

go func(batch, i int, name string) {
	defer wg.Done()
	results[batch][i] = "done:" + name
}(batch, i, name)
for batch, rows := range results {
	fmt.Println(batch, rows)
}
results[batch] = make([]string, len(page))

Interactive Tools for This Topic

FAQ

What does WaitGroup Reuse Across Batch Phases print when run?
Invoke the file as-is — the `batch` prefixes identify which step printed each line.