Golang / GoLang Interfaces and Object Oriented Interview Questions
What is sync.Locker and how is it used in real-world Go concurrency code?
sync.Locker is a small two-method interface from the standard library. It is satisfied by both *sync.Mutex and *sync.RWMutex, as well as any custom lock type. It is used to write generic lock-based utilities.
// sync.Locker interface:
type Locker interface {
Lock()
Unlock()
}
// Both *sync.Mutex and *sync.RWMutex satisfy Locker
var mu sync.Mutex
var rwmu sync.RWMutex
var l1 sync.Locker = &mu // *Mutex satisfies Locker
var l2 sync.Locker = &rwmu // *RWMutex satisfies Locker (Lock/Unlock = write lock)
// Generic utility using sync.Locker
func withLock(l sync.Locker, fn func()) {
l.Lock()
defer l.Unlock()
fn()
}
counter := 0
withLock(&mu, func() { counter++ })
// sync.Cond uses Locker — works with any lock
cond := sync.NewCond(&mu) // &mu satisfies Locker
// Or with an RWMutex read lock:
cond2 := sync.NewCond(rwmu.RLocker()) // RLocker() returns a Locker for the read lock
// Custom lock satisfying Locker
type SpinLock struct{ locked atomic.Bool }
func (s *SpinLock) Lock() { for !s.locked.CompareAndSwap(false, true) { runtime.Gosched() } }
func (s *SpinLock) Unlock() { s.locked.Store(false) }
var spin SpinLock
withLock(&spin, func() { counter++ }) // SpinLock works with withLock!sync.Locker is an excellent example of Go's philosophy: a small, well-named interface that abstracts just one behaviour (mutual exclusion). The withLock utility pattern is idiomatic — it ensures Unlock is always called via defer, avoiding forgotten unlocks.
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...
