forked from agtorre/go-cookbook
-
Notifications
You must be signed in to change notification settings - Fork 0
/
map.go
40 lines (32 loc) · 742 Bytes
/
map.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
package atomic
import (
"errors"
"sync"
)
// SafeMap uses a mutex to allow
// getting and setting in a thread-safe way
type SafeMap struct {
m map[string]string
mu *sync.RWMutex
}
// NewSafeMap creates a SafeMap
func NewSafeMap() SafeMap {
return SafeMap{m: make(map[string]string), mu: &sync.RWMutex{}}
}
// Set uses a write lock and sets the value given
// a key
func (t *SafeMap) Set(key, value string) {
t.mu.Lock()
defer t.mu.Unlock()
t.m[key] = value
}
// Get uses a RW lock and gets the value if it exists,
// otherwise an error is returned
func (t *SafeMap) Get(key string) (string, error) {
t.mu.RLock()
defer t.mu.RUnlock()
if v, ok := t.m[key]; ok {
return v, nil
}
return "", errors.New("key not found")
}