diff options
| author | chrislusf <chrislu@Chriss-MacBook-Air.local> | 2014-12-08 20:29:25 -0800 |
|---|---|---|
| committer | chrislusf <chrislu@Chriss-MacBook-Air.local> | 2014-12-08 20:29:25 -0800 |
| commit | 52180f386b044af7a6daba3e33ff04b5e9da25ba (patch) | |
| tree | 1490ad6c11f986da12a421e717767402dc993d3c /go/util/concurrent_read_map.go | |
| parent | ba972694c730429889c696bd9853a38843f64f65 (diff) | |
| download | seaweedfs-52180f386b044af7a6daba3e33ff04b5e9da25ba.tar.xz seaweedfs-52180f386b044af7a6daba3e33ff04b5e9da25ba.zip | |
Add read-write lock to guard topology changes on new collections and ttls.
Diffstat (limited to 'go/util/concurrent_read_map.go')
| -rw-r--r-- | go/util/concurrent_read_map.go | 37 |
1 files changed, 37 insertions, 0 deletions
diff --git a/go/util/concurrent_read_map.go b/go/util/concurrent_read_map.go new file mode 100644 index 000000000..d16fdbcaf --- /dev/null +++ b/go/util/concurrent_read_map.go @@ -0,0 +1,37 @@ +package util + +import "sync" + +// A mostly for read map, which can thread-safely +// initialize the map entries. +type ConcurrentReadMap struct { + rmutex sync.RWMutex + mutex sync.Mutex + 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.mutex.Lock() + defer m.mutex.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.rmutex.RLock() + if value, ok := m.Items[key]; ok { + m.rmutex.RUnlock() + return value + } else { + m.rmutex.RUnlock() + return m.initMapEntry(key, newEntry) + } +} |
