Lesson 13 of 60 · Go
Concurrency Primer: Goroutines
Duration: 20 minutes
Goroutines
This lesson explains the main concept clearly with beginner-friendly examples and background so you can learn why the code works.
A goroutine is a lightweight thread managed by the Go runtime.
func say(msg string) {
for i := 0; i < 3; i++ {
fmt.Println(msg)
}
}
func main() {
go say("world") // runs concurrently
say("hello") // runs in main goroutine
}
Scheduling
- The runtime multiplexes many goroutines onto a small set of OS threads.
- The default GOMAXPROCS is the number of logical CPUs.
Synchronizing with sync.WaitGroup
var wg sync.WaitGroup
for i := 0; i < 5; i++ {
wg.Add(1)
go func(id int) {
defer wg.Done()
fmt.Println("worker", id)
}(i)
}
wg.Wait()