Pass Locks Via The sync.Locker Interface
Depend on the sync.Locker interface so helpers accept any lock: Mutex directly and RWMutex through RLocker().
Code
package main
import (
"fmt"
"sync"
)
// 只依赖 sync.Locker 接口:调用方可以换锁实现
func withLock(l sync.Locker, critical func()) {
l.Lock()
defer l.Unlock()
critical()
}
func main() {
var mu sync.Mutex
counter := 0
var wg sync.WaitGroup
for i := 0; i < 4; i++ {
wg.Add(1)
go func() {
defer wg.Done()
withLock(&mu, func() {
counter++
})
}()
}
wg.Wait()
fmt.Println("counter:", counter)
// RWMutex 通过 RLocker 也能满足 Locker 接口
var rw sync.RWMutex
withLock(rw.RLocker(), func() {
fmt.Println("read lock acquired")
})
}How the snippet works
Under the hood: the functions withLock and main.
Repetition is confined to for i := 0; i < 4; i++ — the rest of the file is straight-line. A goroutine takes the work off the current one. The cleanup call is deferred to function exit — success, early return, and panic all covered.
Points of care
- Built-in APIs only — no supply chain needs to be vetted.
Using it
The signature you will reach for first is func withLock(l sync.Locker, critical func())
The demo output is labeled (counter:, read lock acquired), so every line of output can be traced to the operation that made it.
Execute the file and main walks through withLock, in that order.
Key statements
func withLock(l sync.Locker, critical func()) {
l.Lock()
defer l.Unlock()
critical()
}
var wg sync.WaitGroup
var rw sync.RWMutex
Interactive Tools for This Topic
cURL to Python & Go ConverterTranslate curl CLI commands with headers, auth, JSON bodies, and timeouts into ready-to-run Python requests and Go net/http client code snippets.HTTP Retry & Backoff CalculatorSimulate exponential backoff retry schedules with Full, Equal, Decorrelated, or No Jitter to inspect per-attempt wait times and cumulative latency.
FAQ
- What does Pass Locks Via The sync.Locker Interface print when run?
- Running the file directly is enough — expect labeled output lines such as `counter:`, `read lock acquired`.
Report a problem with this exampleOpens a pre-filled issue on GitHub.