19#include <condition_variable>
53 for (std::size_t i = 0; i < N; ++i)
76 template<
class F,
typename ...Args>
77 auto queue(F&& f, Args&&... args) -> std::future<
decltype(f(args...))>
84 using RetType =
decltype(f(args...));
85 auto ptr = std::make_shared< std::packaged_task<RetType()> >(std::forward<F>(f), std::forward<Args>(args)...);
86 auto taskFunc = [ptr]() {
if (ptr->valid()) (*ptr)(); };
88 auto r=ptr->get_future();
90 std::unique_lock<std::mutex> l(
m_mutex);
91 m_work.emplace_back(taskFunc);
103 std::unique_lock<std::mutex> l(
m_mutex);
121 std::function<void()> f;
124 std::unique_lock<std::mutex> l(
m_mutex);
129 f = std::move(
m_work.front());
145 std::deque< std::function<void()> >
m_work;
void finish()
finish enques a "stop the thread" message for every thread, then waits for them to finish
~ThreadPool()
deletes the thread pool by finishing all threads
std::deque< std::function< void()> > m_work
ThreadPool(std::size_t N=1)
start N threads in the thread pool.
ThreadPool(const ThreadPool &)=delete
auto queue(F &&f, Args &&... args) -> std::future< decltype(f(args...))>
Queue the callable function f for the threads to execute.
std::vector< std::future< void > > m_finished
ThreadPool(ThreadPool &&)=delete
ThreadPool & operator=(ThreadPool &&)=delete
std::condition_variable m_cond
ThreadPool & operator=(const ThreadPool &)=delete