-
Notifications
You must be signed in to change notification settings - Fork 2
/
varrw.go
62 lines (50 loc) · 1.28 KB
/
varrw.go
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
package multilock
import (
"sync"
)
// VarRW is a variable length structure of sync.RWMutex
type VarRW struct {
length int
mutexes []sync.RWMutex
distribution func(i interface{}, length int) int
global sync.Mutex
}
// NewVarRW creates a variable length structure of sync.RWMutex
func NewVarRW(length int, opts ...Option) *VarRW {
var options options
for _, opt := range opts {
opt.apply(&options)
}
if options.distribution == nil {
options.distribution = distribution
}
return &VarRW{
length: length,
distribution: options.distribution,
mutexes: make([]sync.RWMutex, length),
}
}
// Get retrieves a sync.RWMutex from an interface
func (m *VarRW) Get(i interface{}) *sync.RWMutex {
return m.GetID(addr(i))
}
// GetID retrieves a sync.RWMutex from an identifier
func (m *VarRW) GetID(id string) *sync.RWMutex {
m.global.Lock()
defer m.global.Unlock()
index := m.distribution(id, m.length)
return &m.mutexes[index]
}
// Resize the internal multilock structure
func (m *VarRW) Resize(length int, opts ...Option) {
m.global.Lock()
defer m.global.Unlock()
var options options
for _, opt := range opts {
opt.apply(&options)
}
if options.distribution != nil {
m.distribution = options.distribution
}
m.mutexes = make([]sync.RWMutex, length)
}