The sync package provides basic synchronization primitives like WaitGroup, Mutex, and Once to coordinate goroutines. Use sync.WaitGroup to wait for a collection of goroutines to finish, sync.Mutex to protect shared data, or sync.Once to ensure a function runs exactly once.
package main
import (
"fmt"
"sync"
)
func main() {
var wg sync.WaitGroup
wg.Add(2)
go func() {
defer wg.Done()
fmt.Println("Goroutine 1")
}()
go func() {
defer wg.Done()
fmt.Println("Goroutine 2")
}()
wg.Wait()
fmt.Println("Done")
}