Mutex — exclusive lock (one goroutine at a time). RWMutex — read-write lock (multiple readers OR one writer).
sync.Mutex:
Lock() — acquires exclusive access.Unlock() — releases the lock.sync.RWMutex:
RLock()/RUnlock() — shared read access.Lock()/Unlock() — exclusive write access.1// Thread-safe cache with RWMutex2type Cache struct {3 mu sync.RWMutex4 data map[string]interface{}5}67func (c *Cache) Get(key string) (interface{}, bool) {8 c.mu.RLock()9 defer c.mu.RUnlock()10 val, ok := c.data[key]11 return val, ok12}1314func (c *Cache) Set(key string, value interface{}) {15 c.mu.Lock()16 defer c.mu.Unlock()17 c.data[key] = value18}
When to use RWMutex:
When to use Mutex:
Common mistakes:
defer Unlock() (deadlock on panic).