Wait for goroutines to finish
suggest changeGo programs end when the main function ends, so it is common practice to wait for all goroutines to finish.
A common solution is a sync.WaitGroup.
var wg sync.WaitGroup // 1
func routine(i int) {
defer wg.Done() // 3
fmt.Printf("routine %v finished\n", i)
}
func main() {
wg.Add(10) // 2
for i := 0; i < 10; i++ {
go routine(i) // *
}
wg.Wait() // 4
fmt.Println("main finished")
}
routine 9 finished
routine 0 finished
routine 1 finished
routine 2 finished
routine 3 finished
routine 4 finished
routine 5 finished
routine 6 finished
routine 7 finished
routine 8 finished
main finished
WaitGroup usage in order of execution:
- Declaration of a global variable. Making it global is the easiest way to make it visible to all functions and methods.
- Increasing the counter. This must be done in the goroutine that calls
Wait, before the new goroutines run. There is no guarantee that a newly started goroutine will execute before step 4 (sync.WaitGroup). - Decreasing the counter. This must be done at the exit of a goroutine. By using a deferred call, we make sure that it will be called whenever the function ends, no matter how it ends.
- Waiting for the counter to reach 0. This must be done in the main goroutine to prevent the program from exiting before all goroutines have finished.
Parameters are evaluated before starting a new goroutine.
go routine(i) therefore passes the current value of i into routine. wg.Add(10) runs in main before the loop, so the counter already includes all ten goroutines when wg.Wait is called.
Found a mistake? Have a question or improvement idea?
Let me know.
Table Of Contents