From 588b59cfa114e94b3e5b612f3fed65bd7bb0ba5d Mon Sep 17 00:00:00 2001 From: Jakob Progsch Date: Thu, 25 Sep 2014 12:06:19 +0200 Subject: [PATCH] Check stop condition under lock. Use emplace instead of push. --- ThreadPool.h | 11 ++++++----- 1 file changed, 6 insertions(+), 5 deletions(-) diff --git a/ThreadPool.h b/ThreadPool.h index 0235c8b..b6d95d7 100644 --- a/ThreadPool.h +++ b/ThreadPool.h @@ -60,10 +60,6 @@ auto ThreadPool::enqueue(F&& f, Args&&... args) -> std::future::type> { typedef typename std::result_of::type 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 >( std::bind(std::forward(f), std::forward(args)...) @@ -72,7 +68,12 @@ auto ThreadPool::enqueue(F&& f, Args&&... args) std::future res = task->get_future(); { std::unique_lock lock(queue_mutex); - tasks.push([task](){ (*task)(); }); + + // don't allow enqueueing after stopping the pool + if(stop) + throw std::runtime_error("enqueue on stopped ThreadPool"); + + tasks.emplace([task](){ (*task)(); }); } condition.notify_one(); return res;