9 #include <condition_variable> 17 template<
class F,
class... Args>
18 auto enqueue(F&& f, Args&&... args)
19 -> std::future<
typename std::result_of<F(Args...)>::type>;
23 std::vector< std::thread > workers;
25 std::queue< std::function<void()> > tasks;
28 std::mutex queue_mutex;
29 std::condition_variable condition;
34 inline ThreadPool::ThreadPool(
size_t threads)
37 for(
size_t i = 0;i<threads;++i)
43 std::function<void()> task;
46 std::unique_lock<std::mutex> lock(this->queue_mutex);
47 this->condition.wait(lock,
48 [this]{ return this->stop || !this->tasks.empty(); });
49 if(this->stop && this->tasks.empty())
51 task = std::move(this->tasks.front());
62 template<
class F,
class... Args>
63 auto ThreadPool::enqueue(F&& f, Args&&... args)
64 -> std::future<
typename std::result_of<F(Args...)>::type>
66 using return_type =
typename std::result_of<F(Args...)>::type;
68 auto task = std::make_shared< std::packaged_task<return_type()> >(
69 std::bind(std::forward<F>(f), std::forward<Args>(args)...)
72 std::future<return_type> res = task->get_future();
74 std::unique_lock<std::mutex> lock(queue_mutex);
78 throw std::runtime_error(
"enqueue on stopped ThreadPool");
80 tasks.emplace([task](){ (*task)(); });
82 condition.notify_one();
87 inline ThreadPool::~ThreadPool()
90 std::unique_lock<std::mutex> lock(queue_mutex);
93 condition.notify_all();
94 for(std::thread &worker: workers)
Definition: ThreadPool.h:14