How to Use sync.Mutex and sync.RWMutex in Go

Use sync.Mutex for exclusive access to shared data and sync.RWMutex to allow multiple readers but only one writer at a time.

Use sync.Mutex to protect shared data when multiple goroutines read and write, and sync.RWMutex when reads far outnumber writes to allow concurrent reading. Lock the mutex before accessing the data and unlock it immediately after to prevent race conditions.

var mu sync.Mutex
var count int

mu.Lock()
count++
mu.Unlock()

// For read-heavy workloads
var rwmu sync.RWMutex
rwmu.RLock()
val := count
rwmu.RUnlock()