Golang / GoLang Basics Interview Questions
What is sync.Mutex and when do you use sync.RWMutex instead?
sync.Mutex provides mutual exclusion — at most one goroutine holds the lock at any moment. sync.RWMutex is an extension: multiple goroutines can hold a read lock simultaneously, but a write lock is exclusive. Use RWMutex when reads vastly outnumber writes.
// sync.Mutex — protect any shared mutable state
type SafeCounter struct {
mu sync.Mutex
count int
}
func (c *SafeCounter) Add(n int) {
c.mu.Lock()
defer c.mu.Unlock() // always use defer — runs even on panic
c.count += n
}
func (c *SafeCounter) Value() int {
c.mu.Lock()
defer c.mu.Unlock()
return c.count
}
// sync.RWMutex — read-heavy workloads (e.g. config, caches)
type SafeConfig struct {
mu sync.RWMutex
data map[string]string
}
func (c *SafeConfig) Get(key string) string {
c.mu.RLock() // multiple goroutines can hold RLock at once
defer c.mu.RUnlock()
return c.data[key]
}
func (c *SafeConfig) Set(key, val string) {
c.mu.Lock() // exclusive — no readers OR writers allowed
defer c.mu.Unlock()
c.data[key] = val
}
// RULES:
// 1. Never copy a Mutex after first use (lock state would be duplicated)
// 2. Always pass struct containing Mutex as a pointer (*SafeCounter)
// 3. Mutex is NOT reentrant — a goroutine holding Lock() will deadlock
// if it calls Lock() again on the same mutex
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...
