From db55263b4c25a5014ce72aa1b601cfdebfe5d176 Mon Sep 17 00:00:00 2001 From: moneromooo-monero Date: Mon, 23 Apr 2018 18:53:38 +0100 Subject: [PATCH] threadpool: allow constructing an object, and misc tweaks use unsigned int to avoid having to range check negative numbers, use const where possible, don't needlessly create empty objects, use std::move where possible --- src/common/threadpool.cpp | 8 ++++---- src/common/threadpool.h | 14 +++++++++----- 2 files changed, 13 insertions(+), 9 deletions(-) diff --git a/src/common/threadpool.cpp b/src/common/threadpool.cpp index 51e071577..fb238dca7 100644 --- a/src/common/threadpool.cpp +++ b/src/common/threadpool.cpp @@ -39,11 +39,11 @@ static __thread int depth = 0; namespace tools { -threadpool::threadpool() : running(true), active(0) { +threadpool::threadpool(unsigned int max_threads) : running(true), active(0) { boost::thread::attributes attrs; attrs.set_stack_size(THREAD_STACK_SIZE); - max = tools::get_max_concurrency(); - size_t i = max; + max = max_threads ? max_threads : tools::get_max_concurrency(); + unsigned int i = max; while(i--) { threads.push_back(boost::thread(attrs, boost::bind(&threadpool::run, this))); } @@ -78,7 +78,7 @@ void threadpool::submit(waiter *obj, std::function f) { } } -int threadpool::get_max_concurrency() { +unsigned int threadpool::get_max_concurrency() const { return max; } diff --git a/src/common/threadpool.h b/src/common/threadpool.h index 34152541c..bf80a87f6 100644 --- a/src/common/threadpool.h +++ b/src/common/threadpool.h @@ -46,6 +46,9 @@ public: static threadpool instance; return instance; } + static threadpool *getNewForUnitTests(unsigned max_threads = 0) { + return new threadpool(max_threads); + } // The waiter lets the caller know when all of its // tasks are completed. @@ -66,11 +69,12 @@ public: // task to finish. void submit(waiter *waiter, std::function f); - int get_max_concurrency(); + unsigned int get_max_concurrency() const; + + ~threadpool(); private: - threadpool(); - ~threadpool(); + threadpool(unsigned int max_threads = 0); typedef struct entry { waiter *wo; std::function f; @@ -79,8 +83,8 @@ public: boost::condition_variable has_work; boost::mutex mutex; std::vector threads; - int active; - int max; + unsigned int active; + unsigned int max; bool running; void run(); };