-
Notifications
You must be signed in to change notification settings - Fork 1
Expand file tree
/
Copy pathsafeMap.go
More file actions
60 lines (47 loc) · 1.12 KB
/
safeMap.go
File metadata and controls
60 lines (47 loc) · 1.12 KB
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
package safecollections
import "sync"
// Map type that can be safely shared between
// goroutines that require read/write access to a map
type safeMap struct {
sync.RWMutex
items map[string]string
}
func newSafeMap(size int) *safeMap {
m := make (map[string]string, size)
mutex := sync.RWMutex{}
return &safeMap{mutex, m}
}
// Concurrent map item
type safeMapItem struct {
Key string
Value string
}
// Sets a key in a concurrent map
func (sMap *safeMap) Set(key string, value string ){
sMap.Lock()
defer sMap.Unlock()
sMap.items[key] = value
}
// Gets a key from a concurrent map
func (sMap *safeMap) Get(key string) (string, bool) {
sMap.Lock()
defer sMap.Unlock()
value, ok := sMap.items[key]
return value, ok
}
// Iterates over the items in a concurrent map
// Each item is sent over a channel, so that
// we can iterate over the map using the builtin range keyword
func (sMap *safeMap) Iter() <-chan safeMapItem {
mapItem := make(chan safeMapItem)
f := func() {
sMap.Lock()
defer sMap.Unlock()
for k, v := range sMap.items {
mapItem <- safeMapItem{k, v}
}
close(mapItem)
}
go f()
return mapItem
}