Sync Primitives in Go

From the Go cheat sheet · Concurrency · verified Jul 2026

Sync Primitives

Mutex, WaitGroup, and Once for synchronization

go
// WaitGroup: wait for goroutines
var wg sync.WaitGroup
for i := range 5 {
    wg.Add(1)
    go func() {
        defer wg.Done()
        fmt.Println(i)
    }()
}
wg.Wait()

// Mutex: protect shared state
var mu sync.Mutex
mu.Lock()
// critical section
mu.Unlock()
📌 Always defer wg.Done() and mu.Unlock() to prevent deadlocks
💡 Use RWMutex when reads vastly outnumber writes
🎯 sync.Once is perfect for lazy initialization
⚡ Prefer channels for communication, mutexes for state protection

More Go tasks

Back to the full Go cheat sheet