Pass Locks Via The sync.Locker Interface

Depend on the sync.Locker interface so helpers accept any lock: Mutex directly and RWMutex through RLocker().

GoResilience

Code

gosnippet
37 lines
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

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`.