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

kzh125 · · 4664 次点击
benchmark_test.go ``` package xsync import ( "testing" ) func BenchmarkUtil(b *testing.B) { var i = 0 u := NewUtil() b.ResetTimer() b.RunParallel(func(pb *testing.PB) { for pb.Next() { locker, _ := u.Locker("test") locker.Lock() i++ locker.Unlock() locker.Close() } }) } func BenchmarkXsync(b *testing.B) { var i = 0 l := NewMultilocker() b.ResetTimer() b.RunParallel(func(pb *testing.PB) { for pb.Next() { mu := l.Get("test") mu.Lock() i++ mu.Unlock() l.Put("test") } }) } ```
#10
更多评论
………… 一个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