1 #ifndef THREADPOOL_H_INCLUDED 2 #define THREADPOOL_H_INCLUDED 32 #include <condition_variable> 88 void add_thread(std::function<
void()> initializer);
90 template<
class F,
class... Args>
100 -> std::future<
typename std::result_of<F(Args...)>::type>;
111 m_threads.emplace_back([
this, initializer] {
114 std::function<void()> task;
116 std::unique_lock<std::mutex> lock(
m_mutex);
121 task = std::move(
m_tasks.front());
130 for (
size_t i = 0; i < threads; i++) {
135 template<
class F,
class... Args>
137 -> std::future<
typename std::result_of<F(Args...)>::type> {
138 using return_type =
typename std::result_of<F(Args...)>::type;
140 auto task = std::make_shared< std::packaged_task<return_type()> >(
141 std::bind(std::forward<F>(f), std::forward<Args>(args)...)
144 std::future<return_type> res = task->get_future();
146 std::unique_lock<std::mutex> lock(m_mutex);
147 m_tasks.emplace([task](){(*task)();});
149 m_condvar.notify_one();
155 std::unique_lock<std::mutex> lock(
m_mutex);
181 template<
class F,
class... Args>
void add_thread(std::function< void()> initializer)
Add an extra thread.
Definition: ThreadPool.h:110
auto add_task(F &&f, Args &&... args) -> std::future< typename std::result_of< F(Args...)>::type >
Add a task to the thread.
Definition: ThreadPool.h:136
ThreadGroup(ThreadPool &pool)
Build a ThreadGroup from a ThreadPool.
Definition: ThreadPool.h:179
void add_task(F &&f, Args &&... args)
Add a task to the thread.
Definition: ThreadPool.h:189
ThreadPool & m_pool
Definition: ThreadPool.h:206
std::mutex m_mutex
Definition: ThreadPool.h:105
An implementation of Thread group.
Definition: ThreadPool.h:171
An implementation of Thread pool.
Definition: ThreadPool.h:57
ThreadPool()=default
Default constructor.
std::vector< std::future< void > > m_taskresults
Definition: ThreadPool.h:207
std::condition_variable m_condvar
Definition: ThreadPool.h:106
std::vector< std::thread > m_threads
Definition: ThreadPool.h:102
~ThreadPool()
Default destructor.
Definition: ThreadPool.h:153
std::queue< std::function< void()> > m_tasks
Definition: ThreadPool.h:103
void wait_all()
Wait until all task results have a valid value.
Definition: ThreadPool.h:200
A set of useful method and class.
Definition: Random.cpp:33
bool m_exit
Definition: ThreadPool.h:107
void initialize(std::size_t)
Create worker threads.
Definition: ThreadPool.h:129