Start goroutines and wait for completion
Start goroutines and wait for completion
A go statement schedules a function call independently. Its return values are discarded; main must arrange to receive any result. A sync.WaitGroup is a completion counter, not a result container. Register work before launching it, call Done exactly once per registered task, and call Wait before reading the finished results. A zero-value WaitGroup is ready to use.
package main
import ( "fmt" "sync")
func main() { var wg sync.WaitGroup var result int wg.Add(1) go func() { defer wg.Done(); result = 7 * 6 }() wg.Wait() fmt.Println(result)}Defer runs Done when the goroutine function returns. Done synchronizes before the return of the Wait it unblocks, making the completed write visible to main. A sleep is not a substitute for synchronization. Do not copy a WaitGroup after first use, and do not put the initial Add inside the newly started goroutine: Wait could return before Add runs.
Expected output:
42Collect independent results in input order
package main
import ( "fmt" "sync")
func main() { inputs := []int{3, 5, 2} results := make([]int, len(inputs)) var wg sync.WaitGroup for i, n := range inputs { wg.Add(1) go func(i, n int) { defer wg.Done(); results[i] = n * n }(i, n) } wg.Wait() fmt.Println(results)}Each goroutine owns a separate element of a preallocated slice. The slice header is not modified while workers run. No append or concurrent read of an unfinished element occurs. Printing only after Wait ensures stable order even when tasks complete in a different order. Use explicit parameters to keep the loop example independent of historical loop-variable capture rules.
Expected output:
[9 25 4]Try it locally
For inputs [4, 1, 6], start one goroutine per input to double it. Preallocate the output, wait, and print in input order.
Check Your Understanding
Solidify your learning with the interactive assessment directly below this lesson.
Concept Quiz & Questions
Concurrency foundations 02: Start goroutines and wait for completion
Check the lesson objective before moving on.
Where should the initial positive Add occur?
Why is the slice example safe?