WaitGroup Go Starts And Joins Goroutines

WaitGroup Go starts each goroutine with Add and Done already handled, so fan-out code becomes a single closure call before one Wait joins everything.

GoData Integrity

Code

gosnippet
34 lines
package main

import (
	"fmt"
	"slices"
	"sync"
)

func squares(ids []int) []int {
	var (
		wg      sync.WaitGroup
		mu      sync.Mutex
		results []int
	)

	for _, id := range ids {
		// Go 1.25 的 WaitGroup.Go:内部先 Add(1),闭包返回后自动 Done
		wg.Go(func() {
			mu.Lock()
			results = append(results, id*id)
			mu.Unlock()
		})
	}

	wg.Wait()
	return results
}

func main() {
	sq := squares([]int{2, 5, 9})
	// goroutine 完成顺序不定,展示前先排序
	slices.Sort(sq)
	fmt.Println("squares:", sq)
}

Inside the snippet

WaitGroup Go Starts And Joins Goroutines keeps everything in the functions squares and main.

The cycling part of this snippet is for _, id := range ids.

Using it

The main signature, verbatim, is func squares(ids []int) []int

The demo output is labeled (squares:), so the printed output reads as a trace of the operations performed.

Execute the file and main walks through squares, in that order.

Key statements

for _, id := range ids {
// Go 1.25 的 WaitGroup.Go:内部先 Add(1),闭包返回后自动 Done
wg.Go(func() {
mu.Lock()
results = append(results, id*id)
mu.Unlock()
})
}
func main() {
sq := squares([]int{2, 5, 9})
// goroutine 完成顺序不定,展示前先排序
slices.Sort(sq)
fmt.Println("squares:", sq)
}
wg      sync.WaitGroup

Interactive Tools for This Topic

FAQ

What does WaitGroup Go Starts And Joins Goroutines print when run?
Run it as a complete program — the output lines carry labels such as `squares:`.