Mutex — exclusive lock. RWMutex — read-write lock with concurrent reads.
sync.Mutex:
Lock()/Unlock() — exclusive access.sync.RWMutex:
RLock()/RUnlock() — shared reads.Lock()/Unlock() — exclusive writes.1// Mutex for simple counter2var mu sync.Mutex3var count int45func increment() {6 mu.Lock()7 defer mu.Unlock()8 count++9}1011// RWMutex for cache12var rwmu sync.RWMutex13var cache map[string]string1415func get(key string) (string, bool) {16 rwmu.RLock()17 defer rwmu.RUnlock()18 val, ok := cache[key]19 return val, ok20}2122func set(key, value string) {23 rwmu.Lock()24 defer rwmu.Unlock()25 cache[key] = value26}
When to use RWMutex:
When to use Mutex:
Common mistakes:
defer Unlock().