31 #include <condition_variable>
45 template<
class F,
class ... Args>
46 auto enqueue(F&& f, Args&&... args) -> std::future<
typename std::result_of<F(Args...)>::type>;
51 std::vector<std::thread> _workers;
53 std::queue<std::function<void()> > _tasks;
56 std::mutex _queueMutex;
57 std::condition_variable _condition;
58 std::atomic_bool _stop;
62 inline ThreadPool::ThreadPool(
size_t threads) :
64 _workers.reserve(threads);
65 for (
size_t i = 0; i < threads; ++i) {
66 _workers.emplace_back([
this] {
68 std::function<void()> task;
70 std::unique_lock<std::mutex> lock(this->_queueMutex);
71 this->_condition.wait(lock, [
this] {
72 return this->_stop || !this->_tasks.empty();
74 if (this->_stop && this->_tasks.empty()) {
77 task = std::move(this->_tasks.front());
88 template<
class F,
class ... Args>
90 -> std::future<
typename std::result_of<F(Args...)>::type> {
91 using return_type =
typename std::result_of<F(Args...)>::type;
93 auto task = std::make_shared<std::packaged_task<return_type()> >(std::bind(std::forward<F>(f), std::forward<Args>(args)...));
95 std::future<return_type> res = task->get_future();
97 std::unique_lock<std::mutex> lock(_queueMutex);
98 _tasks.emplace([task]() {(*task)();});
100 _condition.notify_one();
105 inline ThreadPool::~ThreadPool() {
107 _condition.notify_all();
108 for (std::thread &worker : _workers)
Definition: ThreadPool.h:38
auto enqueue(F &&f, Args &&...args) -> std::future< typename std::result_of< F(Args...)>::type >
Definition: ThreadPool.h:89