Overview
Goroutines are lightweight concurrent functions in Go that run independently and are managed by the Go runtime scheduler rather than the operating system.In general, program execution can be divided into two types of routines:
- Main Routine: The main routine is the first goroutine that starts when a Go program runs. It executes the
main()function in the main package and determines the lifetime of the entire program. When the main routine finishes, the program exits immediately even if other goroutines are still running. - Child Routine: A child routine is any goroutine started from another routine using the
gokeyword. It runs concurrently with the routine that created it and performs work independently. A child routine does not block its parent unless synchronization is explicitly implemented. It finishes when its function returns or when the program terminates.
Basic Usage
WaitGroup
In Go, aWaitGroup from the sync package is used to wait for a collection of goroutines to finish before continuing execution in the main routine.