aboutsummaryrefslogtreecommitdiff
path: root/go/util/concurrent_read_map.go
diff options
context:
space:
mode:
authorChris Lu <chris.lu@gmail.com>2016-05-30 12:30:26 -0700
committerChris Lu <chris.lu@gmail.com>2016-05-30 12:30:26 -0700
commit6df18a918103634fd4e5e3297e9d2b1597ec5b73 (patch)
tree7d0e918cd4a04348eb2edf67f7951835ca20011d /go/util/concurrent_read_map.go
parent46a89a7d61a269dbf8cfb1d113d328f138ac5361 (diff)
downloadseaweedfs-6df18a918103634fd4e5e3297e9d2b1597ec5b73.tar.xz
seaweedfs-6df18a918103634fd4e5e3297e9d2b1597ec5b73.zip
rwlock concurrent read map
Diffstat (limited to 'go/util/concurrent_read_map.go')
-rw-r--r--go/util/concurrent_read_map.go44
1 files changed, 33 insertions, 11 deletions
diff --git a/go/util/concurrent_read_map.go b/go/util/concurrent_read_map.go
index ca1109f22..bbf303d82 100644
--- a/go/util/concurrent_read_map.go
+++ b/go/util/concurrent_read_map.go
@@ -7,31 +7,53 @@ import (
// A mostly for read map, which can thread-safely
// initialize the map entries.
type ConcurrentReadMap struct {
- rmutex sync.RWMutex
- Items map[string]interface{}
+ sync.RWMutex
+
+ items map[string]interface{}
}
func NewConcurrentReadMap() *ConcurrentReadMap {
- return &ConcurrentReadMap{Items: make(map[string]interface{})}
+ return &ConcurrentReadMap{items: make(map[string]interface{})}
}
func (m *ConcurrentReadMap) initMapEntry(key string, newEntry func() interface{}) (value interface{}) {
- m.rmutex.Lock()
- defer m.rmutex.Unlock()
- if value, ok := m.Items[key]; ok {
+ m.Lock()
+ defer m.Unlock()
+ if value, ok := m.items[key]; ok {
return value
}
value = newEntry()
- m.Items[key] = value
+ m.items[key] = value
return value
}
func (m *ConcurrentReadMap) Get(key string, newEntry func() interface{}) interface{} {
- m.rmutex.RLock()
- if value, ok := m.Items[key]; ok {
- m.rmutex.RUnlock()
+ m.RLock()
+ if value, ok := m.items[key]; ok {
+ m.RUnlock()
return value
}
- m.rmutex.RUnlock()
+ m.RUnlock()
return m.initMapEntry(key, newEntry)
}
+
+func (m *ConcurrentReadMap) Find(key string) (interface{}, bool) {
+ m.RLock()
+ value, ok := m.items[key]
+ m.RUnlock()
+ return value, ok
+}
+
+func (m *ConcurrentReadMap) Items() (itemsCopy []interface{}) {
+ m.RLock()
+ for _, i := range m.items {
+ itemsCopy = append(itemsCopy, i)
+ }
+ return itemsCopy
+}
+
+func (m *ConcurrentReadMap) Delete(key string) {
+ m.Lock()
+ delete(m.items, key)
+ m.Unlock()
+}