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 = μ // *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(μ, func() { counter++ }) // sync.Cond uses Locker â works with any lock cond := sync.NewCond(μ) // μ 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.
More Related questions...