in go when a main go routine starts a new go routine it doesn’t wait for the new go routine to finish, and continuous the execute the following lines of code, but once it reaches the end, the entire program get terminated no matter if the new go routines are finished or not
example:
import (
"fmt"
"time"
)
func main() {
//new go routine
go func() {
for {
time.Sleep(1 * time.Second)
fmt.Println("go")
}
}()
fmt.Println("main")
}
here even though the function is calling an infinite loop in the go routine the program ends as soon as it completes the main function,
to prevent this from happening and to wait for go routine to finish we can use sync.WaitGroup
sync.WaitGroup :
A WaitGroup waits for a collection of goroutines to finish. The main goroutine calls Add to set the number of goroutines to wait for. Then each of the goroutines runs and calls Done when finished. At the same time, Wait can be used to block until all goroutines have finished.
here by using wait group the main program waits for the completion of the go routine to complete
package main
import (
"fmt"
"sync"
"time"
)
func main() {
//new go routine
var wg sync.WaitGroup
wg.Add(1)
go func() {
for {
time.Sleep(1 * time.Second)
fmt.Println("go")
}
wg.Done()
}()
fmt.Println("main")
wg.Wait()
}
Add:
func (wg *[WaitGroup](<https://pkg.go.dev/sync#WaitGroup>)) Add(delta [int](<https://pkg.go.dev/builtin#int>))
Add adds delta, which may be negative, to the WaitGroup counter. If the counter becomes zero, all goroutines blocked on Wait are released. If the counter goes negative, Add panics.
Done:
func (wg *[WaitGroup](<https://pkg.go.dev/sync#WaitGroup>)) Done()