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.
Invest now in Acorns!!! 🚀
Join Acorns and get your $5 bonus!
Acorns is a micro-investing app that automatically invests your "spare change" from daily purchases into diversified, expert-built portfolios of ETFs. It is designed for beginners, allowing you to start investing with as little as $5. The service automates saving and investing. Disclosure: I may receive a referral bonus.
Invest now!!! Get Free equity stock (US, UK only)!
Use Robinhood app to invest in stocks. It is safe and secure. Use the Referral link to claim your free stock when you sign up!.
The Robinhood app makes it easy to trade stocks, crypto and more.
Webull! Receive free stock by signing up using the link: Webull signup.
More Related questions...
