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
More Related questions...