forked from dollarkillerx/async_utils
-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathconcurrent_hash_map.go
More file actions
59 lines (47 loc) · 954 Bytes
/
concurrent_hash_map.go
File metadata and controls
59 lines (47 loc) · 954 Bytes
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
package async_utils
import (
"fmt"
"sync"
)
type mapItem struct {
data interface{}
mu sync.RWMutex
}
type ConcurrentHashMap struct {
db map[string]*mapItem
mu sync.RWMutex
}
func NewConcurrentHashMap() *ConcurrentHashMap {
return &ConcurrentHashMap{
db: map[string]*mapItem{},
}
}
func (c *ConcurrentHashMap) Insert(key string, val interface{}) {
item, ex := c.db[key]
if !ex {
c.db[key] = &mapItem{
data: val,
}
return
}
item.mu.Lock()
defer item.mu.Unlock()
item.data = val
}
func (c *ConcurrentHashMap) Get(key string) (interface{}, error) {
item, ex := c.db[key]
if !ex {
return nil, fmt.Errorf("not found")
}
item.mu.RLock()
defer item.mu.RUnlock()
return item.data, nil
}
type IterationFunc = func(key string, val interface{})
func (c *ConcurrentHashMap) Iteration(iterationFunc IterationFunc) {
for k := range c.db {
c.db[k].mu.RLock()
iterationFunc(k, c.db[k].data)
c.db[k].mu.RUnlock()
}
}