-
Notifications
You must be signed in to change notification settings - Fork 2
/
var.go
62 lines (50 loc) · 1.25 KB
/
var.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"
)
// Var is a variable length structure of sync.Mutex
type Var struct {
length int
mutexes []sync.Mutex
distribution func(i interface{}, length int) int
global sync.Mutex
}
// NewVar creates a variable length structure of sync.Mutex
func NewVar(length int, opts ...Option) *Var {
var options options
for _, opt := range opts {
opt.apply(&options)
}
if options.distribution == nil {
options.distribution = distribution
}
return &Var{
length: length,
distribution: options.distribution,
mutexes: make([]sync.Mutex, length),
}
}
// Get retrieves a sync.Mutex from an interface
func (m *Var) Get(i interface{}) *sync.Mutex {
return m.GetID(addr(i))
}
// GetID retrieves a sync.Mutex from an identifier
func (m *Var) GetID(id string) *sync.Mutex {
m.global.Lock()
defer m.global.Unlock()
index := m.distribution(id, m.length)
return &m.mutexes[index]
}
// Resize the internal multilock structure
func (m *Var) 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.Mutex, length)
}