From 33f59debf224924cc735f2f6ed69e8c14bae404a Mon Sep 17 00:00:00 2001 From: Evgeniy Kulikov Date: Tue, 27 Aug 2019 16:32:52 +0300 Subject: [PATCH] store: Fix DataRace in MemoryStore - Add RWMutex to MemoryStore struct - Use Lock/Unlock for writing - Use RLock/RUnlock for reading - Fix #313 issue --- pkg/core/storage/memory_store.go | 9 ++++++++- 1 file changed, 8 insertions(+), 1 deletion(-) diff --git a/pkg/core/storage/memory_store.go b/pkg/core/storage/memory_store.go index de705a911..e5fae863b 100644 --- a/pkg/core/storage/memory_store.go +++ b/pkg/core/storage/memory_store.go @@ -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 }