Sobes.tech
Middle+

What is the difference between RWMutex and a regular Mutex?

sobes.tech AI

Answer from AI

Mutex is a standard mutex lock that provides exclusive access to a resource: only one goroutine can acquire the mutex at a time.

RWMutex (Read-Write Mutex) extends functionality by allowing:

  • Multiple goroutines to acquire read locks simultaneously (many readers).
  • A single goroutine to acquire a write lock, blocking all readers and other writers.

Thus, RWMutex improves performance in scenarios where read operations far outnumber write operations, allowing data to be read concurrently without mutual blocking.

Example usage:

var mu sync.RWMutex
var data int

// Reading
mu.RLock()
value := data
mu.RUnlock()

// Writing
mu.Lock()
data = 42
mu.Unlock()

Using a regular Mutex would block other operations even during reads, which can reduce performance when reads are frequent.