Add conservative locking arond Caching/HTTP FLs

Making them hopefully thread-safe.
This commit is contained in:
Simonas Kazlauskas committed 2017-06-24 21:06:18 +03:00
1 parent 3f63c29736
commit 597a1af85c
4 files changed
+65 -75

No files matched your search

+7 -19
View File
@@ -25,19 +25,16 @@
// Takes ownership of backend.
CachingFileLoader::CachingFileLoader(FileLoader *backend)
: filesize_(0), backend_(backend), exists_(-1), isDirectory_(-1), aheadThread_(false), prepared_(false) {
: filesize_(0), backend_(backend), exists_(-1), isDirectory_(-1), aheadThread_(false) {
}
void CachingFileLoader::Prepare() {
if (prepared_) {
return;
}
prepared_ = true;
filesize_ = backend_->FileSize();
if (filesize_ > 0) {
InitCache();
}
std::call_once(preparedFlag_, [this](){
filesize_ = backend_->FileSize();
if (filesize_ > 0) {
InitCache();
}
});
}
CachingFileLoader::~CachingFileLoader() {
@@ -50,7 +47,6 @@ CachingFileLoader::~CachingFileLoader() {
bool CachingFileLoader::Exists() {
if (exists_ == -1) {
std::lock_guard<std::mutex> guard(backendMutex_);
exists_ = backend_->Exists() ? 1 : 0;
}
return exists_ == 1;
@@ -58,7 +54,6 @@ bool CachingFileLoader::Exists() {
bool CachingFileLoader::ExistsFast() {
if (exists_ == -1) {
std::lock_guard<std::mutex> guard(backendMutex_);
return backend_->ExistsFast();
}
return exists_ == 1;
@@ -66,7 +61,6 @@ bool CachingFileLoader::ExistsFast() {
bool CachingFileLoader::IsDirectory() {
if (isDirectory_ == -1) {
std::lock_guard<std::mutex> guard(backendMutex_);
isDirectory_ = backend_->IsDirectory() ? 1 : 0;
}
return isDirectory_ == 1;
@@ -78,7 +72,6 @@ s64 CachingFileLoader::FileSize() {
}
std::string CachingFileLoader::Path() const {
std::lock_guard<std::mutex> guard(backendMutex_);
return backend_->Path();
}
@@ -92,7 +85,6 @@ size_t CachingFileLoader::ReadAt(s64 absolutePos, size_t bytes, void *data, Flag
size_t readSize = 0;
if ((flags & Flags::HINT_UNCACHED) != 0) {
std::lock_guard<std::mutex> guard(backendMutex_);
readSize = backend_->ReadAt(absolutePos, bytes, data, flags);
} else {
readSize = ReadFromCache(absolutePos, bytes, data);
@@ -186,9 +178,7 @@ void CachingFileLoader::SaveIntoCache(s64 pos, size_t bytes, Flags flags, bool r
blocksMutex_.unlock();
u8 *buf = new u8[BLOCK_SIZE];
backendMutex_.lock();
backend_->ReadAt(cacheStartPos << BLOCK_SHIFT, BLOCK_SIZE, buf, flags);
backendMutex_.unlock();
blocksMutex_.lock();
// While blocksMutex_ was unlocked, another thread may have read.
@@ -202,9 +192,7 @@ void CachingFileLoader::SaveIntoCache(s64 pos, size_t bytes, Flags flags, bool r
blocksMutex_.unlock();
u8 *wholeRead = new u8[blocksToRead << BLOCK_SHIFT];
backendMutex_.lock();
backend_->ReadAt(cacheStartPos << BLOCK_SHIFT, blocksToRead << BLOCK_SHIFT, wholeRead, flags);
backendMutex_.unlock();
blocksMutex_.lock();
for (size_t i = 0; i < blocksToRead; ++i) {