Mutex — provides exclusive access (only one goroutine at a time). RWMutex — allows concurrent reads but exclusive writes.
sync.Mutex:
Lock() acquires exclusive access.Unlock() releases the lock.1var mu sync.Mutex23func Read() {4 mu.Lock()5 defer mu.Unlock()6 // Read shared data — exclusive access7}89func Write() {10 mu.Lock()11 defer mu.Unlock()12 // Modify shared data — exclusive access13}
sync.RWMutex:
RLock() / RUnlock() — multiple goroutines can read simultaneously.Lock() / Unlock() — exclusive write access.1var rwmu sync.RWMutex23func Read() {4 rwmu.RLock()5 defer rwmu.RUnlock()6 // Read shared data — multiple goroutines can read7}89func Write() {10 rwmu.Lock()11 defer rwmu.Unlock()12 // Modify shared data — exclusive access13}
When to use RWMutex:
When to use Mutex:
Common mistakes:
defer for unlocking (can lead to deadlocks on panics).