updated Store.GetOrSet to lock first with RLock/RUnlock
This commit is contained in:
parent
d3ca24e509
commit
00da008d64
|
@ -151,17 +151,19 @@ func (s *Store[T]) Set(key string, value T) {
|
||||||
// GetOrSet retrieves a single existing value for the provided key
|
// GetOrSet retrieves a single existing value for the provided key
|
||||||
// or stores a new one if it doesn't exist.
|
// or stores a new one if it doesn't exist.
|
||||||
func (s *Store[T]) GetOrSet(key string, setFunc func() T) T {
|
func (s *Store[T]) GetOrSet(key string, setFunc func() T) T {
|
||||||
s.mu.Lock()
|
// lock only reads to minimize locks contention
|
||||||
defer s.mu.Unlock()
|
s.mu.RLock()
|
||||||
|
v, ok := s.data[key]
|
||||||
|
s.mu.RUnlock()
|
||||||
|
|
||||||
|
if !ok {
|
||||||
|
s.mu.Lock()
|
||||||
|
v = setFunc()
|
||||||
if s.data == nil {
|
if s.data == nil {
|
||||||
s.data = make(map[string]T)
|
s.data = make(map[string]T)
|
||||||
}
|
}
|
||||||
|
|
||||||
v, ok := s.data[key]
|
|
||||||
if !ok {
|
|
||||||
v = setFunc()
|
|
||||||
s.data[key] = v
|
s.data[key] = v
|
||||||
|
s.mu.Unlock()
|
||||||
}
|
}
|
||||||
|
|
||||||
return v
|
return v
|
||||||
|
|
Loading…
Reference in New Issue