The main goroutine
- Go course
- Intermediate
- Lesson 4/80
- 4 min
Learn that the main function itself is a goroutine.
The main goroutine
The main function itself is a goroutine: the main goroutine. When the program starts the Go runtime launches main; when main ends all other goroutines die at once.
So if you start a goroutine and immediately exit main you never see its output. You must wait for it first: with time.Sleep, a channel or sync.WaitGroup.
time.Sleep is simple but unreliable; production code prefers channels or WaitGroup. The duration may not be enough.
Waiting methods
Three common ways to wait for goroutines:
time.Sleep: simple but fragilesync.WaitGroup: counts, releases when zero- channel: goroutine sends a done signal
WaitGroup is the most common production choice. wg.Add(1) increments, the goroutine calls wg.Done() to decrement, the main program blocks on wg.Wait().
Practice Print from the main goroutine
Inside main, add a fmt.Println line and print main goroutine with fmt.Println.
Starter code
package main
import "fmt"
func main() {
// buraya yaz
}Sample solution
package main
import "fmt"
func main() {
fmt.Println("ana goroutine")
}Expected output
ana goroutine
Questions and answers
Review the lesson questions together with their answers. To test yourself, solve the lesson interactively.
1 What happens to goroutines when main exits?
- They are waited for
- They die immediately Correct answer
- Moved to a channel
- Continue in the background
Explanation: they die immediately. Go goroutines cannot outlive the main program.
2 WaitGroup waiting
var wg sync.WaitGroup
wg.Add(1)
go func() {
defer wg.Done()
work()
}()
____
var wg sync.WaitGroup
wg.Add(1)
go func() {
defer wg.Done()
work()
}()
wg.Wait()
Explanation: wg.Wait() blocks the main program.
3 Match waiting methods
| Term | Meaning |
|---|---|
time.Sleep |
Fragile |
WaitGroup |
Production |
channel |
Signal |
main |
Main goroutine |