开发了一个基于key的加锁方案

kzh125 · · 4664 次点击
``` Running tool: /home/jarlyyn/goroot/go1.13/bin/go test -benchmem -run=^$ -bench . goos: linux goarch: amd64 BenchmarkUtil-12 8520894 136 ns/op 87 B/op 2 allocs/op BenchmarkXsync-12 1460154 834 ns/op 104 B/op 2 allocs/op PASS ok _/tmp/test 3.364s ```
#11
更多评论
………… 一个sync.Map,值是sync.Mutex类型就可以了……
#1
找了下我的代码,大概是这样的 func NewUtil() *Util { return &Util{ locks: &sync.Map{}, } } type Util struct { locks *sync.Map } func (u *Util) Locker(key string) (*Locker, bool) { newlocker := &Locker{ Map: u.locks, Key: key, } v, ok := u.locks.LoadOrStore(key, newlocker) return v.(*Locker), ok } type Locker struct { sync.RWMutex Map *sync.Map Key string } func (l *Locker) Unlock() { l.RWMutex.Unlock() l.Map.Delete(l.Key) }
#2