File
Blob: util/atomic/keyed_mutex.go
| 1 | package atomic |
| 2 | |
| 3 | import ( |
| 4 | "sync" |
| 5 | |
| 6 | "github.com/zeebo/xxh3" |
| 7 | ) |
| 8 | |
| 9 | const shardSize = 128 |
| 10 | |
| 11 | type KeyedRWMutex struct { |
| 12 | noCopy |
| 13 | mutexes [shardSize]sync.RWMutex |
| 14 | } |
| 15 | |
| 16 | func NewKeyedRWMutex() *KeyedRWMutex { |
| 17 | return &KeyedRWMutex{} |
| 18 | } |
| 19 | |
| 20 | func (m *KeyedRWMutex) obtain(key string) *sync.RWMutex { |
| 21 | i := xxh3.HashString(key) % shardSize |
| 22 | return &m.mutexes[i] |
| 23 | } |
| 24 | |
| 25 | func (m *KeyedRWMutex) Lock(key string) func() { |
| 26 | mu := m.obtain(key) |
| 27 | mu.Lock() |
| 28 | |
| 29 | return mu.Unlock |
| 30 | } |
| 31 | |
| 32 | func (m *KeyedRWMutex) RLock(key string) func() { |
| 33 | mu := m.obtain(key) |
| 34 | mu.RLock() |
| 35 | |
| 36 | return mu.RUnlock |
| 37 | } |