Check stop condition under lock. Use emplace instead of push.

This commit is contained in:
Jakob Progsch
2014-09-25 12:06:19 +02:00
parent 20061c5c7f
commit 588b59cfa1

View File

@@ -60,10 +60,6 @@ auto ThreadPool::enqueue(F&& f, Args&&... args)
-> std::future<typename std::result_of<F(Args...)>::type>
{
typedef typename std::result_of<F(Args...)>::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<return_type()> >(
std::bind(std::forward<F>(f), std::forward<Args>(args)...)
@@ -72,7 +68,12 @@ auto ThreadPool::enqueue(F&& f, Args&&... args)
std::future<return_type> res = task->get_future();
{
std::unique_lock<std::mutex> 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;