Sobes.tech
Senior

What is Mutex and RWMutex? How do they differ?

sobes.tech AI

Answer from AI

Mutex (in Go — sync.Mutex) is a synchronization primitive that provides exclusive access to a resource. When one goroutine acquires the Mutex, other goroutines attempting to acquire it are blocked until it is released.

RWMutex (sync.RWMutex) is an extension of Mutex that allows dividing access into read and write. It permits multiple goroutines to read data simultaneously (RLock), but writing (Lock) requires exclusive access and blocks all readers and writers.

Differences:

  • Mutex blocks everyone trying to access while it is held.
  • RWMutex allows multiple readers to work in parallel, but writing blocks everyone.

Example:

var mu sync.RWMutex
var data int

// Reading
mu.RLock()
fmt.Println(data)
mu.RUnlock()

// Writing
mu.Lock()
data = 42
mu.Unlock()
What is Mutex and RWMutex? How do they differ? — Golang - sobes.tech