Junior — Middle
How can you guaranteedly complete the execution of all running goroutines in a program?
sobes.tech AI
Answer from AI
In Go, there is no built-in way to forcibly terminate a goroutine from outside. To reliably wait for all launched goroutines to finish, synchronization is usually done using sync.WaitGroup.
How it works:
- Before starting each goroutine, call
wg.Add(1). - Inside the goroutine, call
wg.Done()at the end. - In the main function, call
wg.Wait(), which blocks execution until the counter reaches zero.
Example:
var wg sync.WaitGroup
wg.Add(1)
go func() {
defer wg.Done()
// goroutine work
}()
wg.Wait() // wait for all goroutines to finish
This way, the program will reliably wait for all goroutines to finish before continuing or exiting.