Browse Source
Add read-write lock to guard topology changes on new collections and ttls.
pull/38/head
Add read-write lock to guard topology changes on new collections and ttls.
pull/38/head
chrislusf
10 years ago
5 changed files with 74 additions and 34 deletions
-
21go/topology/collection.go
-
29go/topology/topology.go
-
7go/topology/topology_map.go
-
14go/topology/topology_vacuum.go
-
37go/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) |
|||
} |
|||
} |
Write
Preview
Loading…
Cancel
Save
Reference in new issue