From 41600c13f7c8eec90cca6253b66972169e3cc7cc Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?Sebastian=20Me=C3=9Fmer?= Date: Sun, 29 Mar 2015 08:36:09 -0400 Subject: [PATCH] Introduce a mutex for OpenBlockList --- implementations/synchronized/OpenBlockList.cpp | 8 +++++++- implementations/synchronized/OpenBlockList.h | 3 +++ 2 files changed, 10 insertions(+), 1 deletion(-) diff --git a/implementations/synchronized/OpenBlockList.cpp b/implementations/synchronized/OpenBlockList.cpp index 7a90e092..d0d014ba 100644 --- a/implementations/synchronized/OpenBlockList.cpp +++ b/implementations/synchronized/OpenBlockList.cpp @@ -22,16 +22,18 @@ OpenBlockList::~OpenBlockList() { } unique_ptr OpenBlockList::insert(unique_ptr block) { + lock_guard lock(_mutex); auto insertResult = _openBlocks.insert(block->key()); assert(insertResult.second == true); return make_unique(std::move(block), this); } unique_ptr OpenBlockList::acquire(const Key &key, function ()> loader) { - //TODO Think it through, whether we really don't need any locks here. + unique_lock lock(_mutex); auto insertResult = _openBlocks.insert(key); auto blockWasNotOpenYet = insertResult.second; if (blockWasNotOpenYet) { + lock.unlock(); auto block = loader(); if (block.get() == nullptr) { return nullptr; @@ -39,6 +41,7 @@ unique_ptr OpenBlockList::acquire(const Key &key, function(std::move(block), this); } else { auto blockFuture = _addPromiseForBlock(key); + lock.unlock(); return blockFuture.get(); } } @@ -50,6 +53,7 @@ future> OpenBlockList::_addPromiseForBlock(const Key &key) { } void OpenBlockList::release(unique_ptr block) { + lock_guard lock(_mutex); auto foundWantedBlock = _wantedBlocks.find(block->key()); if (foundWantedBlock != _wantedBlocks.end()) { foundWantedBlock->second.set_value(std::move(block)); @@ -63,9 +67,11 @@ void OpenBlockList::release(unique_ptr block) { } void OpenBlockList::close(unique_ptr block, function)> onClose) { + unique_lock lock(_mutex); auto insertResult = _blocksToClose.emplace(block->key(), promise>()); assert(insertResult.second == true); block.reset(); + lock.unlock(); auto closedBlock = insertResult.first->second.get_future().get(); onClose(std::move(closedBlock)); } diff --git a/implementations/synchronized/OpenBlockList.h b/implementations/synchronized/OpenBlockList.h index 5fdea5aa..c892c5ff 100644 --- a/implementations/synchronized/OpenBlockList.h +++ b/implementations/synchronized/OpenBlockList.h @@ -6,6 +6,7 @@ #include #include #include +#include #include "../../utils/Key.h" #include @@ -29,6 +30,8 @@ private: std::set _openBlocks; std::map>> _wantedBlocks; std::map>> _blocksToClose; + //TODO Check whether we need this mutex or whether we can write it threadsafe without a mutex + mutable std::mutex _mutex; std::future> _addPromiseForBlock(const Key &key); };