diff --git a/src/sfizz/FilePool.cpp b/src/sfizz/FilePool.cpp index e637b83f..29ad7efb 100644 --- a/src/sfizz/FilePool.cpp +++ b/src/sfizz/FilePool.cpp @@ -165,6 +165,8 @@ void sfz::FilePool::loadingThread() noexcept // The voice abandoned the promise already we just don't care if (promise.use_count() != 1) { + threadsLoading++; + fs::path file { rootDirectory / std::string(promise->filename) }; SndfileHandle sndFile(reinterpret_cast(file.c_str())); if (sndFile.error() != 0) @@ -174,6 +176,8 @@ void sfz::FilePool::loadingThread() noexcept const uint32_t frames = sndFile.frames(); promise->fileData = readFromFile(sndFile, frames, oversamplingFactor); promise->dataReady = true; + + threadsLoading--; } while (!filledPromiseQueue.try_enqueue(promise)) { @@ -246,3 +250,15 @@ void sfz::FilePool::emptyFileLoadingQueues() noexcept while (emptyQueue) std::this_thread::sleep_for(1ms); } + +void sfz::FilePool::waitForBackgroundLoading() noexcept +{ + // TODO: validate that this is enough, otherwise we will need an atomic count + // of the files we need to load still. + // Spinlocking on the size of the background queue + while (promiseQueue.size_approx() > 0) + std::this_thread::sleep_for(0.1ms); + // Spinlocking on the threads possibly logging in the background + while (threadsLoading > 0) + std::this_thread::sleep_for(0.1ms); +} diff --git a/src/sfizz/FilePool.h b/src/sfizz/FilePool.h index a052200c..9e238953 100644 --- a/src/sfizz/FilePool.h +++ b/src/sfizz/FilePool.h @@ -142,6 +142,7 @@ public: void setOversamplingFactor(Oversampling factor) noexcept; Oversampling getOversamplingFactor() const noexcept; void emptyFileLoadingQueues() noexcept; + void waitForBackgroundLoading() noexcept; private: fs::path rootDirectory; void loadingThread() noexcept; @@ -153,6 +154,7 @@ private: // Signals bool quitThread { false }; bool emptyQueue { false }; + std::atomic threadsLoading { 0 }; std::vector temporaryFilePromises; std::vector promisesToClean;