The sync package in Go provides basic synchronization primitives like Mutex, WaitGroup, and Once to coordinate access to shared data across goroutines. Use sync.Mutex to protect critical sections, sync.WaitGroup to wait for a collection of goroutines to finish, and sync.Once to ensure a function runs exactly once.
package main
import (
"fmt"
"sync"
)
func main() {
var mu sync.Mutex
var wg sync.WaitGroup
var once sync.Once
count := 0
wg.Add(3)
for i := 0; i < 3; i++ {
go func() {
defer wg.Done()
mu.Lock()
count++
mu.Unlock()
if i == 0 {
once.Do(func() { fmt.Println("Initialized once") })
}
}()
}
wg.Wait()
fmt.Println("Final count:", count)
}