From 6b2ec66ffafbad0aa1eef3a2c59d30dda033be2c Mon Sep 17 00:00:00 2001 From: Jean Pierre Cimalando Date: Mon, 19 Oct 2020 16:53:55 +0200 Subject: [PATCH] Ref-count the global thread pool --- src/sfizz/FilePool.cpp | 28 +++++++++++++++++++++++++--- src/sfizz/FilePool.h | 3 +++ 2 files changed, 28 insertions(+), 3 deletions(-) diff --git a/src/sfizz/FilePool.cpp b/src/sfizz/FilePool.cpp index 115198cd..fbeca154 100644 --- a/src/sfizz/FilePool.cpp +++ b/src/sfizz/FilePool.cpp @@ -47,7 +47,29 @@ #endif #include "threadpool/ThreadPool.h" using namespace std::placeholders; -static ThreadPool threadPool { std::thread::hardware_concurrency() > 2 ? std::thread::hardware_concurrency() - 2 : 1 }; + +static std::weak_ptr globalThreadPoolWeakPtr; +static std::mutex globalThreadPoolMutex; + +static std::shared_ptr globalThreadPool() +{ + std::shared_ptr threadPool; + + threadPool = globalThreadPoolWeakPtr.lock(); + if (threadPool) + return threadPool; + + std::lock_guard lock(globalThreadPoolMutex); + threadPool = globalThreadPoolWeakPtr.lock(); + if (threadPool) + return threadPool; + + unsigned numThreads = std::thread::hardware_concurrency(); + numThreads = (numThreads > 2) ? (numThreads - 2) : 1; + threadPool.reset(new ThreadPool(numThreads)); + globalThreadPoolWeakPtr = threadPool; + return threadPool; +} void readBaseFile(sfz::AudioReader& reader, sfz::FileAudioBuffer& output, uint32_t numFrames) { @@ -96,7 +118,7 @@ void streamFromFile(sfz::AudioReader& reader, uint32_t numFrames, sfz::Oversampl } sfz::FilePool::FilePool(sfz::Logger& logger) - : logger(logger) + : logger(logger), threadPool(globalThreadPool()) { loadingJobs.reserve(config::maxVoices); lastUsedFiles.reserve(config::maxVoices); @@ -478,7 +500,7 @@ void sfz::FilePool::dispatchingJob() noexcept if (filesToLoad.try_pop(queuedData)) { loadingJobs.push_back( - threadPool.enqueue([this](const QueuedFileData& data) { loadingJob(data); }, queuedData)); + threadPool->enqueue([this](const QueuedFileData& data) { loadingJob(data); }, queuedData)); } // Clear finished jobs diff --git a/src/sfizz/FilePool.h b/src/sfizz/FilePool.h index a44ce948..a9f0ecff 100644 --- a/src/sfizz/FilePool.h +++ b/src/sfizz/FilePool.h @@ -44,6 +44,7 @@ #include #include #include "utility/SpinMutex.h" +class ThreadPool; namespace sfz { using FileAudioBuffer = AudioBuffer garbageToCollect; + std::shared_ptr threadPool; + // Preloaded data absl::flat_hash_map preloadedFiles; absl::flat_hash_map loadedFiles;