Mutex — exclusive lock for mutual exclusion. RWMutex — read-write lock allowing concurrent reads but exclusive writes.
sync.Mutex:
Lock()/Unlock() for all operations.sync.RWMutex:
RLock()/RUnlock() for reads (concurrent).Lock()/Unlock() for writes (exclusive).1// RWMutex for config store2type ConfigStore struct {3 mu sync.RWMutex4 configs map[string]string5}67func (s *ConfigStore) Get(key string) (string, bool) {8 s.mu.RLock()9 defer s.mu.RUnlock()10 val, ok := s.configs[key]11 return val, ok12}1314func (s *ConfigStore) Set(key, value string) {15 s.mu.Lock()16 defer s.mu.Unlock()17 s.configs[key] = value18}
When to use RWMutex:
When to use Mutex:
Common mistakes:
defer Unlock().