What Is the Difference Between Mutex and RWMutex in Go

Mutex allows exclusive access for any operation, while RWMutex permits multiple concurrent readers but exclusive access for writers.

A sync.Mutex allows only one goroutine to hold the lock at a time, blocking all others, while a sync.RWMutex allows multiple readers or a single writer. Use RWMutex when your data is read frequently but written rarely to improve concurrency.

import "sync"

// Mutex: Exclusive access (Read or Write)
var mu sync.Mutex
mu.Lock()
// Critical section
mu.Unlock()

// RWMutex: Multiple readers OR one writer
var rwmu sync.RWMutex

// Reading (multiple allowed)
rwmu.RLock()
// Read data
rwmu.RUnlock()

// Writing (exclusive)
rwmu.Lock()
// Write data
rwmu.Unlock()