/* * This file is licensed under the zlib/libpng license, included in this * distribution in the file COPYING. */ #include #include #include #include #include #include #include #include #ifndef _THREADPOOL_HPP #define _THREADPOOL_HPP namespace thermion { class ThreadPool { std::vector pool; bool stop; std::mutex access; std::condition_variable cond; std::deque> tasks; public: explicit ThreadPool(int nr = 1) : stop(false) { while(nr-->0) { add_worker(); } } ~ThreadPool() { stop = true; for(std::thread &t : pool) { t.join(); } pool.clear(); } template auto add_task(std::packaged_task& pt) -> std::future { std::unique_lock lock(access); auto ret = pt.get_future(); tasks.push_back([pt=std::make_shared>(std::move(pt))]{ (*pt)();}); cond.notify_one(); return ret; } private: void add_worker() { std::thread t([this]() { while(!stop || tasks.size() > 0) { std::function task; { std::unique_lock lock(access); if(tasks.empty()) { cond.wait_for(lock, std::chrono::duration(5)); continue; } task = std::move(tasks.front()); tasks.pop_front(); } task(); } }); pool.push_back(std::move(t)); } }; } #endif//_THREADPOOL_HPP // vim: syntax=cpp11