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()
Think of a Mutex as a single key to a room; only one person can enter at a time to prevent arguments over shared items. An RWMutex is like a room where many people can look at a book together, but only one person can write in it at a time. You use these to stop your program from crashing when different parts try to change the same data simultaneously.