From 5d0ca72d50d315d7e2a4fce9fc4c89ca34793249 Mon Sep 17 00:00:00 2001 From: Jakob Progsch Date: Sun, 17 Feb 2013 11:10:40 +0100 Subject: [PATCH] Simplifications and fixes Replaced deque by a queue (which by default uses a deque). Simplified the task packaging as suggested by Ang3lus in issue #4. The destructor now waits for the queue to empty but throws a std::runtime_error if enqueue is called on the stopped pool (see issue #3). --- ThreadPool.h | 55 +++++++++++++--------------------------------------- 1 file changed, 14 insertions(+), 41 deletions(-) diff --git a/ThreadPool.h b/ThreadPool.h index ec80d5d..6c75d04 100644 --- a/ThreadPool.h +++ b/ThreadPool.h @@ -2,45 +2,14 @@ #define THREAD_POOL_H #include -#include +#include #include #include #include #include #include - -// need this type to "erase" the return type of the packaged task -struct any_packaged_base { - virtual void execute() = 0; -}; - -template -struct any_packaged : public any_packaged_base { - any_packaged(std::packaged_task &&t) - : task(std::move(t)) - { - } - void execute() - { - task(); - } - std::packaged_task task; -}; - -class any_packaged_task { -public: - template - any_packaged_task(std::packaged_task &&task) - : ptr(new any_packaged(std::move(task))) - { - } - void operator()() - { - ptr->execute(); - } -private: - std::shared_ptr ptr; -}; +#include +#include class ThreadPool; @@ -66,7 +35,7 @@ private: // need to keep track of threads so we can join them std::vector< std::thread > workers; // the task queue - std::deque< any_packaged_task > tasks; + std::queue< std::function > tasks; // synchronization std::mutex queue_mutex; @@ -81,10 +50,10 @@ void Worker::operator()() std::unique_lock lock(pool.queue_mutex); while(!pool.stop && pool.tasks.empty()) pool.condition.wait(lock); - if(pool.stop) + if(pool.stop && pool.tasks.empty()) return; - any_packaged_task task(pool.tasks.front()); - pool.tasks.pop_front(); + std::function task(pool.tasks.front()); + pool.tasks.pop(); lock.unlock(); task(); } @@ -102,11 +71,15 @@ ThreadPool::ThreadPool(size_t threads) template std::future ThreadPool::enqueue(F f) { - std::packaged_task task(f); - std::future res= task.get_future(); + // don't allow enqueueing after stopping the pool + if(stop) + throw std::runtime_error("enqueue on stopped ThreadPool"); + + auto task = std::make_shared< std::packaged_task >(f); + std::future res = task->get_future(); { std::unique_lock lock(queue_mutex); - tasks.push_back(any_packaged_task(std::move(task))); + tasks.push([task](){ (*task)(); }); } condition.notify_one(); return res;