From 41355c071a18372e8f8e004c0adadceeec1c5abe Mon Sep 17 00:00:00 2001 From: Jakob Progsch Date: Fri, 29 Mar 2013 16:26:35 +0100 Subject: [PATCH] Pass task by universal reference and variadics As suggested by daniel-j-h tasks are now taken by universal reference and forwarded with std::forward. Also enqueue takes a variadic argument list and binds the arguments to the task. --- ThreadPool.h | 14 ++++++++------ example.cpp | 2 +- 2 files changed, 9 insertions(+), 7 deletions(-) diff --git a/ThreadPool.h b/ThreadPool.h index 6c75d04..567ca52 100644 --- a/ThreadPool.h +++ b/ThreadPool.h @@ -26,8 +26,8 @@ private: class ThreadPool { public: ThreadPool(size_t); - template - std::future enqueue(F f); + template + auto enqueue(F&& f, Args&&... args) -> std::future(f)(std::forward(args)...))>; ~ThreadPool(); private: friend class Worker; @@ -68,15 +68,17 @@ ThreadPool::ThreadPool(size_t threads) } // add new work item to the pool -template -std::future ThreadPool::enqueue(F f) +template +auto ThreadPool::enqueue(F&& f, Args&&... args) -> std::future(f)(std::forward(args)...))> { + typedef decltype(std::forward(f)(std::forward(args)...)) return_type; + // 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(); + auto task = std::make_shared< std::packaged_task >(std::bind(std::forward(f), std::forward(args)...)); + std::future res = task->get_future(); { std::unique_lock lock(queue_mutex); tasks.push([task](){ (*task)(); }); diff --git a/example.cpp b/example.cpp index dce6b41..66d6ab7 100644 --- a/example.cpp +++ b/example.cpp @@ -12,7 +12,7 @@ int main() for(int i = 0; i < 8; ++i) { results.push_back( - pool.enqueue([i] { + pool.enqueue([i] { std::cout << "hello " << i << std::endl; std::this_thread::sleep_for(std::chrono::seconds(1)); std::cout << "world " << i << std::endl;