Goroutine creation and termination ordering
Goroutine creation and termination ordering
The go statement synchronizes before the started goroutine begins execution. Goroutine exit alone supplies no corresponding join guarantee. A completion channel or WaitGroup provides explicit ordering for results.
package main
import ( "fmt")
func main() { message := "ready" c := make(chan string) go func() { c <- message }() fmt.Println(<-c)}The initial write occurs before the go statement, so the child sees it. The receive also ensures main waits for the message. Do not mutate message concurrently merely because it was initialized before launch.
Expected output:
readyJoin with WaitGroup
package main
import ( "fmt" "sync")
func main() { var wg sync.WaitGroup var answer int wg.Add(1) go func() { defer wg.Done(); answer = 81 }() wg.Wait() fmt.Println(answer)}Done synchronizes before the return of a Wait it unblocks. Add happens before launch, and the write precedes Done. The group is not a mutex: multiple writers to the same location still need separate protection. Main returning ends the program even if other goroutines remain.
Expected output:
81Try it locally
Use WaitGroup to publish the length of "Go" from one worker; print 2.
Check Your Understanding
Solidify your learning with the interactive assessment directly below this lesson.
Concept Quiz & Questions
Memory model 03: Goroutine creation and termination ordering
Check the lesson objective before moving on.
Which ordering is guaranteed at launch?
What makes the final read safe in the WaitGroup example?