diff --git a/COPYING b/COPYING index c57ee2d..7d69178 100644 --- a/COPYING +++ b/COPYING @@ -1,4 +1,4 @@ -Copyright (c) 2012 Jakob Progsch +Copyright (c) 2012 Jakob Progsch, Václav Zeman This software is provided 'as-is', without any express or implied warranty. In no event will the authors be held liable for any damages diff --git a/ThreadPool.h b/ThreadPool.h index 0235c8b..4183203 100644 --- a/ThreadPool.h +++ b/ThreadPool.h @@ -40,14 +40,18 @@ inline ThreadPool::ThreadPool(size_t threads) { for(;;) { - std::unique_lock lock(this->queue_mutex); - while(!this->stop && this->tasks.empty()) - this->condition.wait(lock); - if(this->stop && this->tasks.empty()) - return; - std::function task(this->tasks.front()); - this->tasks.pop(); - lock.unlock(); + std::function task; + + { + std::unique_lock lock(this->queue_mutex); + this->condition.wait(lock, + [this]{ return this->stop || !this->tasks.empty(); }); + if(this->stop && this->tasks.empty()) + return; + task = std::move(this->tasks.front()); + this->tasks.pop(); + } + task(); } } @@ -59,11 +63,7 @@ template 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"); + using return_type = typename std::result_of::type; auto task = std::make_shared< std::packaged_task >( std::bind(std::forward(f), std::forward(args)...) @@ -72,7 +72,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; @@ -86,8 +91,8 @@ inline ThreadPool::~ThreadPool() stop = true; } condition.notify_all(); - for(size_t i = 0;i > results; for(int i = 0; i < 8; ++i) { - results.push_back( + results.emplace_back( pool.enqueue([i] { std::cout << "hello " << i << std::endl; std::this_thread::sleep_for(std::chrono::seconds(1)); @@ -19,10 +19,10 @@ int main() return i*i; }) ); - } - - for(size_t i = 0;i