Golang / Golang Internals and Memory Management Interview Questions
What is the difference between sync.Mutex and sync.RWMutex and when do you use each?
sync.Mutex is a mutual-exclusion lock: at most one goroutine holds the lock at any time, whether reading or writing. sync.RWMutex distinguishes readers from writers: multiple readers can hold the lock simultaneously (RLock), but a writer requires exclusive access (Lock).
// sync.Mutex â use when all accesses are writes or complex read+write ops type SafeCounter struct { mu sync.Mutex count int } func (c *SafeCounter) Inc() { c.mu.Lock() defer c.mu.Unlock() c.count++ } // sync.RWMutex â use when reads dominate type Config struct { mu sync.RWMutex data map[string]string } func (c *Config) Get(key string) string { c.mu.RLock() // many readers can hold RLock concurrently defer c.mu.RUnlock() return c.data[key] } func (c *Config) Set(key, val string) { c.mu.Lock() // exclusive â no readers or writers defer c.mu.Unlock() c.data[key] = val } // Important: RWMutex is NOT always faster than Mutex // RWMutex has higher per-operation overhead than Mutex // It wins when: read:write ratio >> 10:1 and lock is held for a notable duration // For very short critical sections, Mutex can be faster // TryLock (Go 1.18+) if c.mu.TryLock() { defer c.mu.Unlock() // got the lock } else { // lock is held â do something else }
Writer starvation: in Go's RWMutex, when a writer requests the lock, new readers are blocked even if current readers still hold RLock. This prevents writers from being starved by a continuous stream of readers. The writer waits only for the existing readers to finish, then gets exclusive access.
More Related questions...