Add mutex to fix race condition

This commit is contained in:
Sebastian Messmer 2016-06-29 16:42:43 -07:00
parent 3a447a7110
commit ff0ba06846
3 changed files with 6 additions and 2 deletions

View File

@ -13,6 +13,8 @@ using boost::optional;
using cpputils::unique_ref; using cpputils::unique_ref;
using cpputils::make_unique_ref; using cpputils::make_unique_ref;
using boost::none; using boost::none;
using std::mutex;
using std::unique_lock;
namespace blockstore { namespace blockstore {
namespace caching { namespace caching {
@ -96,10 +98,12 @@ void CachingBlockStore::forEachBlock(std::function<void (const Key &)> callback)
} }
void CachingBlockStore::registerNewBlock(NewBlock *newBlock) { void CachingBlockStore::registerNewBlock(NewBlock *newBlock) {
unique_lock<mutex> lock(_newBlocksMutex);
_newBlocks.insert(newBlock); _newBlocks.insert(newBlock);
} }
void CachingBlockStore::unregisterNewBlock(NewBlock *newBlock) { void CachingBlockStore::unregisterNewBlock(NewBlock *newBlock) {
unique_lock<mutex> lock(_newBlocksMutex);
_newBlocks.erase(newBlock); _newBlocks.erase(newBlock);
} }

View File

@ -38,6 +38,7 @@ private:
cpputils::unique_ref<BlockStore> _baseBlockStore; cpputils::unique_ref<BlockStore> _baseBlockStore;
std::unordered_set<NewBlock*> _newBlocks; // List of all new blocks that aren't in the base store yet. std::unordered_set<NewBlock*> _newBlocks; // List of all new blocks that aren't in the base store yet.
Cache<Key, cpputils::unique_ref<Block>, 1000> _cache; Cache<Key, cpputils::unique_ref<Block>, 1000> _cache;
std::mutex _newBlocksMutex;
DISALLOW_COPY_AND_ASSIGN(CachingBlockStore); DISALLOW_COPY_AND_ASSIGN(CachingBlockStore);
}; };

View File

@ -55,6 +55,7 @@ private:
cpputils::Data _dataWithHeader; cpputils::Data _dataWithHeader;
uint64_t _version; uint64_t _version;
bool _dataChanged; bool _dataChanged;
std::mutex _mutex;
void _storeToBaseBlock(); void _storeToBaseBlock();
static cpputils::Data _prependHeaderToData(uint32_t myClientId, uint64_t version, cpputils::Data data); static cpputils::Data _prependHeaderToData(uint32_t myClientId, uint64_t version, cpputils::Data data);
@ -66,8 +67,6 @@ private:
// This header is prepended to blocks to allow future versions to have compatibility. // This header is prepended to blocks to allow future versions to have compatibility.
static constexpr uint16_t FORMAT_VERSION_HEADER = 0; static constexpr uint16_t FORMAT_VERSION_HEADER = 0;
std::mutex _mutex;
DISALLOW_COPY_AND_ASSIGN(VersionCountingBlock); DISALLOW_COPY_AND_ASSIGN(VersionCountingBlock);
public: public: