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

kzh125 · · 4664 次点击
``` package xsync import "sync" 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) l := v.(*Locker) l.countlocker.Lock() l.count++ l.countlocker.Unlock() return l, ok } type Locker struct { sync.RWMutex Map *sync.Map count int countlocker sync.Mutex Key string } func (l *Locker) Unlock() { l.RWMutex.Unlock() } func (l *Locker) Lock() { l.RWMutex.Lock() } func (l *Locker) Close() { l.countlocker.Lock() l.count-- if l.count == 0 { l.Map.Delete(l.Key) } l.countlocker.Unlock() } ```
#9
更多评论
………… 一个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