mirror of
https://github.com/seaweedfs/seaweedfs.git
synced 2025-09-19 03:39:22 +08:00
directory structure change to work with glide
glide has its own requirements. My previous workaround caused me some code checkin errors. Need to fix this.
This commit is contained in:
60
weed/util/concurrent_read_map.go
Normal file
60
weed/util/concurrent_read_map.go
Normal file
@@ -0,0 +1,60 @@
|
||||
package util
|
||||
|
||||
import (
|
||||
"sync"
|
||||
)
|
||||
|
||||
// A mostly for read map, which can thread-safely
|
||||
// initialize the map entries.
|
||||
type ConcurrentReadMap struct {
|
||||
sync.RWMutex
|
||||
|
||||
items map[string]interface{}
|
||||
}
|
||||
|
||||
func NewConcurrentReadMap() *ConcurrentReadMap {
|
||||
return &ConcurrentReadMap{items: make(map[string]interface{})}
|
||||
}
|
||||
|
||||
func (m *ConcurrentReadMap) initMapEntry(key string, newEntry func() interface{}) (value interface{}) {
|
||||
m.Lock()
|
||||
defer m.Unlock()
|
||||
if value, ok := m.items[key]; ok {
|
||||
return value
|
||||
}
|
||||
value = newEntry()
|
||||
m.items[key] = value
|
||||
return value
|
||||
}
|
||||
|
||||
func (m *ConcurrentReadMap) Get(key string, newEntry func() interface{}) interface{} {
|
||||
m.RLock()
|
||||
if value, ok := m.items[key]; ok {
|
||||
m.RUnlock()
|
||||
return value
|
||||
}
|
||||
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)
|
||||
}
|
||||
m.RUnlock()
|
||||
return itemsCopy
|
||||
}
|
||||
|
||||
func (m *ConcurrentReadMap) Delete(key string) {
|
||||
m.Lock()
|
||||
delete(m.items, key)
|
||||
m.Unlock()
|
||||
}
|
Reference in New Issue
Block a user