store: Fix DataRace in MemoryStore
- Add RWMutex to MemoryStore struct - Use Lock/Unlock for writing - Use RLock/RUnlock for reading - Fix #313 issue
This commit is contained in:
parent
0beb63fd47
commit
33f59debf2
1 changed files with 8 additions and 1 deletions
|
@ -2,11 +2,13 @@ package storage
|
|||
|
||||
import (
|
||||
"encoding/hex"
|
||||
"sync"
|
||||
)
|
||||
|
||||
// MemoryStore is an in-memory implementation of a Store, mainly
|
||||
// used for testing. Do not use MemoryStore in production.
|
||||
type MemoryStore struct {
|
||||
*sync.RWMutex
|
||||
mem map[string][]byte
|
||||
}
|
||||
|
||||
|
@ -29,12 +31,15 @@ func (b *MemoryBatch) Len() int {
|
|||
// NewMemoryStore creates a new MemoryStore object.
|
||||
func NewMemoryStore() *MemoryStore {
|
||||
return &MemoryStore{
|
||||
mem: make(map[string][]byte),
|
||||
RWMutex: new(sync.RWMutex),
|
||||
mem: make(map[string][]byte),
|
||||
}
|
||||
}
|
||||
|
||||
// Get implements the Store interface.
|
||||
func (s *MemoryStore) Get(key []byte) ([]byte, error) {
|
||||
s.RLock()
|
||||
defer s.RUnlock()
|
||||
if val, ok := s.mem[makeKey(key)]; ok {
|
||||
return val, nil
|
||||
}
|
||||
|
@ -43,7 +48,9 @@ func (s *MemoryStore) Get(key []byte) ([]byte, error) {
|
|||
|
||||
// Put implements the Store interface.
|
||||
func (s *MemoryStore) Put(key, value []byte) error {
|
||||
s.Lock()
|
||||
s.mem[makeKey(key)] = value
|
||||
s.Unlock()
|
||||
return nil
|
||||
}
|
||||
|
||||
|
|
Loading…
Reference in a new issue