mirror of
https://github.com/seaweedfs/seaweedfs.git
synced 2024-01-19 02:48:24 +00:00
c67aee7012
It seems that we did not use the feture of rwlock now. delete the sync.Mutex only use sync.RWMutex.
38 lines
817 B
Go
38 lines
817 B
Go
package util
|
|
|
|
import (
|
|
"sync"
|
|
)
|
|
|
|
// A mostly for read map, which can thread-safely
|
|
// initialize the map entries.
|
|
type ConcurrentReadMap struct {
|
|
rmutex 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.rmutex.Lock()
|
|
defer m.rmutex.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
|
|
}
|
|
m.rmutex.RUnlock()
|
|
return m.initMapEntry(key, newEntry)
|
|
}
|