-
Notifications
You must be signed in to change notification settings - Fork 9.4k
/
Copy pathmutexkv.go
49 lines (41 loc) · 1.15 KB
/
mutexkv.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
// Copyright (c) HashiCorp, Inc.
// SPDX-License-Identifier: MPL-2.0
package conns
import (
"sync"
)
// GlobalMutexKV is a global MutexKV for use within this plugin.
var GlobalMutexKV = newMutexKV()
// mutexKV is a simple key/value store for arbitrary mutexes. It can be used to
// serialize changes across arbitrary collaborators that share knowledge of the
// keys they must serialize on.
type mutexKV struct {
lock sync.Mutex
store map[string]*sync.Mutex
}
// Locks the mutex for the given key. Caller is responsible for calling Unlock
// for the same key
func (m *mutexKV) Lock(key string) {
m.get(key).Lock()
}
// Unlock the mutex for the given key. Caller must have called Lock for the same key first
func (m *mutexKV) Unlock(key string) {
m.get(key).Unlock()
}
// Returns a mutex for the given key, no guarantee of its lock status
func (m *mutexKV) get(key string) *sync.Mutex {
m.lock.Lock()
defer m.lock.Unlock()
mutex, ok := m.store[key]
if !ok {
mutex = &sync.Mutex{}
m.store[key] = mutex
}
return mutex
}
// Returns a properly initialized MutexKV
func newMutexKV() *mutexKV {
return &mutexKV{
store: make(map[string]*sync.Mutex),
}
}