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.
This commit is contained in:
Jakob Progsch
2013-03-29 16:26:35 +01:00
parent 5d0ca72d50
commit 41355c071a
2 changed files with 9 additions and 7 deletions

View File

@@ -26,8 +26,8 @@ private:
class ThreadPool {
public:
ThreadPool(size_t);
template<class T, class F>
std::future<T> enqueue(F f);
template<class F, class... Args>
auto enqueue(F&& f, Args&&... args) -> std::future<decltype(std::forward<F>(f)(std::forward<Args>(args)...))>;
~ThreadPool();
private:
friend class Worker;
@@ -68,15 +68,17 @@ ThreadPool::ThreadPool(size_t threads)
}
// add new work item to the pool
template<class T, class F>
std::future<T> ThreadPool::enqueue(F f)
template<class F, class... Args>
auto ThreadPool::enqueue(F&& f, Args&&... args) -> std::future<decltype(std::forward<F>(f)(std::forward<Args>(args)...))>
{
typedef decltype(std::forward<F>(f)(std::forward<Args>(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<T()> >(f);
std::future<T> res = task->get_future();
auto task = std::make_shared< std::packaged_task<return_type()> >(std::bind(std::forward<F>(f), std::forward<Args>(args)...));
std::future<return_type> res = task->get_future();
{
std::unique_lock<std::mutex> lock(queue_mutex);
tasks.push([task](){ (*task)(); });

View File

@@ -12,7 +12,7 @@ int main()
for(int i = 0; i < 8; ++i) {
results.push_back(
pool.enqueue<int>([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;