-
Notifications
You must be signed in to change notification settings - Fork 202
/
mutexHolder.go
51 lines (42 loc) · 1.2 KB
/
mutexHolder.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
package libp2p
import (
"sync"
"github.com/ElrondNetwork/elrond-go/storage"
"github.com/ElrondNetwork/elrond-go/storage/lrucache"
)
// MutexHolder holds a cache of mutexes: pairs of (key, *sync.Mutex)
type MutexHolder struct {
//generalMutex is used to serialize the access to the already concurrent safe lrucache
generalMutex sync.Mutex
mutexes storage.Cacher
}
// NewMutexHolder creates a new instance of MutexHolder with specified capacity.
func NewMutexHolder(mutexesCapacity int) (*MutexHolder, error) {
mh := &MutexHolder{}
var err error
mh.mutexes, err = lrucache.NewCache(mutexesCapacity)
if err != nil {
return nil, err
}
return mh, nil
}
// Get returns a mutex for the provided key. If the key was not found, it will create a new mutex, save it in the
// cache and returns it.
func (mh *MutexHolder) Get(key string) *sync.Mutex {
mh.generalMutex.Lock()
defer mh.generalMutex.Unlock()
sliceKey := []byte(key)
val, ok := mh.mutexes.Get(sliceKey)
if !ok {
newMutex := &sync.Mutex{}
mh.mutexes.Put(sliceKey, newMutex, 0)
return newMutex
}
mutex, ok := val.(*sync.Mutex)
if !ok {
newMutex := &sync.Mutex{}
mh.mutexes.Put(sliceKey, newMutex, 0)
return newMutex
}
return mutex
}