RW Mutexes

A standard sync.Mutex is exclusive: it only allows one goroutine at a time, whether it’s reading or writing. However, maps are actually safe for multiple readers to access at once—they only crash when a writer is involved.

The sync.RWMutex

The RWMutex provides more granular control:

  • RLock() / RUnlock(): Many goroutines can hold a read lock at the same time.
  • Lock() / Unlock(): Only one goroutine can hold a write lock. While locked, all other readers and writers are blocked.

Example

type safeMap struct {
    mu   sync.RWMutex
    data map[string]int
}

// Writers use Lock
func (s *safeMap) Set(key string, val int) {
    s.mu.Lock()
    defer s.mu.Unlock()
    s.data[key] = val
}

// Readers use RLock (Faster for high-read workloads)
func (s *safeMap) Get(key string) int {
    s.mu.RLock()
    defer s.mu.RUnlock()
    return s.data[key]
}

When to use?

Use RWMutex if your data is read far more often than it is written. If you have a roughly equal number of reads and writes, a standard Mutex is often slightly faster due to lower internal overhead.