diff --git a/src/util/ThreadPool.hpp b/src/util/ThreadPool.hpp index c375b445..9acd1902 100644 --- a/src/util/ThreadPool.hpp +++ b/src/util/ThreadPool.hpp @@ -103,14 +103,40 @@ namespace util { } } public: + static constexpr int UNLIMITED = 0; + static constexpr int HALF = -2; + static constexpr int QUARTER = -4; + + /// @brief Main thread pool constructor + /// @param name thread pool name (used in logger) + /// @param workersSupplier workers factory function + /// @param resultConsumer workers results consumer function + /// @param maxWorkers max number of workers. Special values: 0 is + /// unlimited, -2 is half of auto count, -4 is quarter. ThreadPool( std::string name, supplier>> workersSupplier, - consumer resultConsumer + consumer resultConsumer, + int maxWorkers=UNLIMITED ) : logger(std::move(name)), resultConsumer(resultConsumer) { - const uint num_threads = std::thread::hardware_concurrency(); - for (uint i = 0; i < num_threads; i++) { + uint numThreads = std::thread::hardware_concurrency(); + switch (maxWorkers) { + case UNLIMITED: + break; + case HALF: + numThreads = std::max(1U, numThreads); + break; + case QUARTER: + numThreads = std::max(1U, numThreads / 4); + break; + default: + numThreads = std::max( + 1U, std::min(numThreads, static_cast(maxWorkers)) + ); + break; + } + for (uint i = 0; i < numThreads; i++) { threads.emplace_back( &ThreadPool::threadLoop, this, i, workersSupplier() );