Mutex — exclusive lock for mutual exclusion. RWMutex — read-write lock allowing concurrent reads but exclusive writes.
sync.Mutex:
Lock() blocks all other goroutines.Unlock() releases the lock.sync.RWMutex:
RLock()/RUnlock() — multiple readers allowed concurrently.Lock()/Unlock() — exclusive write access.Performance comparison:
1// Mutex — good for write-heavy2var mu sync.Mutex3func update(data int) {4 mu.Lock()5 defer mu.Unlock()6 sharedData = data7}89// RWMutex — good for read-heavy10var rwmu sync.RWMutex11func read() int {12 rwmu.RLock()13 defer rwmu.RUnlock()14 return sharedData15}16func write(data int) {17 rwmu.Lock()18 defer rwmu.Unlock()19 sharedData = data20}
When to use RWMutex:
When to use Mutex:
Common mistakes:
defer mu.Unlock() (deadlock on panic).