Skip to content
File

Blob: util/atomic/keyed_mutex.go

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