From f91ee9cdfae31cd5e6841d32b566abd60618d88f Mon Sep 17 00:00:00 2001 From: Jean Pierre Cimalando Date: Tue, 23 Jun 2020 03:56:56 +0200 Subject: [PATCH] Replace the clearing thread busy wait with semaphore --- src/sfizz/FilePool.cpp | 19 ++++++++++++++----- src/sfizz/FilePool.h | 1 + 2 files changed, 15 insertions(+), 5 deletions(-) diff --git a/src/sfizz/FilePool.cpp b/src/sfizz/FilePool.cpp index 95519ac6..b18d5254 100644 --- a/src/sfizz/FilePool.cpp +++ b/src/sfizz/FilePool.cpp @@ -125,11 +125,16 @@ sfz::FilePool::~FilePool() { quitThread = true; + std::error_code ec; + for (unsigned i = 0; i < threadPool.size(); ++i) { - std::error_code ec; + ec = std::error_code(); workerBarrier.post(ec); } + ec = std::error_code(); + semClearingRequest.post(ec); + for (auto& thread: threadPool) thread.join(); } @@ -360,10 +365,13 @@ void sfz::FilePool::tryToClearPromises() void sfz::FilePool::clearingThread() { - while (!quitThread) { + RTSemaphore& request = semClearingRequest; + do { + request.wait(); + if (quitThread) + return; tryToClearPromises(); - std::this_thread::sleep_for(std::chrono::milliseconds(50)); - } + } while (1); } void sfz::FilePool::loadingThread() noexcept @@ -443,7 +451,8 @@ void sfz::FilePool::cleanupPromises() noexcept auto promiseUsedOnce = [](FilePromisePtr& p) { return p.use_count() == 1; }; auto moveToClear = [&](FilePromisePtr& p) { return promisesToClear.push_back(p); }; - swapAndPopAll(temporaryFilePromises, promiseUsedOnce, moveToClear); + if (swapAndPopAll(temporaryFilePromises, promiseUsedOnce, moveToClear) > 0) + semClearingRequest.post(); } void sfz::FilePool::setOversamplingFactor(sfz::Oversampling factor) noexcept diff --git a/src/sfizz/FilePool.h b/src/sfizz/FilePool.h index 25eaf068..1325168c 100644 --- a/src/sfizz/FilePool.h +++ b/src/sfizz/FilePool.h @@ -275,6 +275,7 @@ private: volatile bool emptyQueue { false }; std::atomic threadsLoading { 0 }; RTSemaphore workerBarrier; + RTSemaphore semClearingRequest; // File promises data structures along with their guards. std::vector emptyPromises;