1 #ifndef THREADPOOL_H_INCLUDED 2 #define THREADPOOL_H_INCLUDED 32 #include <condition_variable> 82 void add_thread(std::function<
void()> initializer);
84 template<
class F,
class... Args>
94 -> std::future<
typename std::result_of<F(Args...)>::type>;
96 std::vector<std::thread> m_threads;
97 std::queue<std::function<void()>> m_tasks;
100 std::condition_variable m_condvar;
105 m_threads.emplace_back([
this, initializer] {
108 std::function<void()> task;
110 std::unique_lock<std::mutex> lock(m_mutex);
111 m_condvar.wait(lock, [
this]{
return m_exit || !m_tasks.empty(); });
112 if (m_exit && m_tasks.empty()) {
115 task = std::move(m_tasks.front());
124 for (
size_t i = 0; i < threads; i++) {
129 template<
class F,
class... Args>
131 -> std::future<
typename std::result_of<F(Args...)>::type> {
132 using return_type =
typename std::result_of<F(Args...)>::type;
134 auto task = std::make_shared< std::packaged_task<return_type()> >(
135 std::bind(std::forward<F>(f), std::forward<Args>(args)...)
138 std::future<return_type> res = task->get_future();
140 std::unique_lock<std::mutex> lock(m_mutex);
141 m_tasks.emplace([task](){(*task)();});
143 m_condvar.notify_one();
149 std::unique_lock<std::mutex> lock(m_mutex);
152 m_condvar.notify_all();
153 for (std::thread & worker: m_threads) {
175 template<
class F,
class... Args>
184 m_taskresults.emplace_back(
185 m_pool.
add_task(std::forward<F>(f), std::forward<Args>(args)...)
195 for (
auto && result: m_taskresults) {
201 std::vector<std::future<void>> m_taskresults;
void add_thread(std::function< void()> initializer)
Add an extra thread.
Definition: ThreadPool.h:104
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:130
ThreadGroup(ThreadPool &pool)
Build a ThreadGroup from a ThreadPool.
Definition: ThreadPool.h:173
void add_task(F &&f, Args &&... args)
Add a task to the thread.
Definition: ThreadPool.h:183
An implementation of Thread group.
Definition: ThreadPool.h:165
An implementation of Thread pool.
Definition: ThreadPool.h:51
ThreadPool()=default
Default constructor.
~ThreadPool()
Default destructor.
Definition: ThreadPool.h:147
void wait_all()
Wait until all task results have a valid value.
Definition: ThreadPool.h:194
A set of useful method and class.
Definition: Random.cpp:27
void initialize(std::size_t)
Create worker threads.
Definition: ThreadPool.h:123