38 #ifndef INCLUDE_OKVIS_THREAD_POOL_HPP_
39 #define INCLUDE_OKVIS_THREAD_POOL_HPP_
41 #include <condition_variable>
50 #include <glog/logging.h>
77 template<
class Function,
class ... Args>
78 std::future<
typename std::result_of<Function(Args...)>::type>
79 enqueue(Function&&
function, Args&&... args);
95 std::queue<std::function<void()>>
tasks_;
109 template<
class Function,
class ... Args>
111 Function&&
function, Args&&... args)
113 typedef typename std::result_of<Function(Args...)>::type return_type;
116 LOG(ERROR)<<
"enqueue() called on stopped ThreadPool";
118 return std::future<
typename std::result_of<Function(Args...)>::type>();
121 auto task = std::make_shared<std::packaged_task<return_type()>>(
122 std::bind(std::forward<Function>(
function), std::forward<Args>(args)...));
124 std::future<return_type> res = task->get_future();
127 tasks_.push([task]() {(*task)();});
135 #endif // INCLUDE_OKVIS_THREAD_POOL_HPP_
std::condition_variable tasks_condition_
A condition variable for worker threads.
Definition: ThreadPool.hpp:99
volatile bool stop_
A signal to stop the threads.
Definition: ThreadPool.hpp:105
This class manages multiple threads and fills them with work.
Definition: ThreadPool.hpp:58
void stop()
Stop the thread pool. This method is non-blocking.
Definition: ThreadPool.hpp:82
~ThreadPool()
Destructor. This joins all threads.
Definition: ThreadPool.cpp:53
std::condition_variable wait_condition_
A condition variable to support waitForEmptyQueue().
Definition: ThreadPool.hpp:101
ThreadPool(size_t numThreads)
Constructor. Launches some amount of workers.
Definition: ThreadPool.cpp:44
void waitForEmptyQueue() const
This method blocks until the queue is empty.
Definition: ThreadPool.cpp:91
std::queue< std::function< void()> > tasks_
The task queue.
Definition: ThreadPool.hpp:95
std::vector< std::thread > workers_
Need to keep track of threads so we can join them.
Definition: ThreadPool.hpp:93
void run()
Run a single thread.
Definition: ThreadPool.cpp:66
unsigned active_threads_
A counter of active threads.
Definition: ThreadPool.hpp:103
std::mutex tasks_mutex_
A mutex to protect the list of tasks.
Definition: ThreadPool.hpp:97
std::future< typename std::result_of< Function(Args...)>::type > enqueue(Function &&function, Args &&...args)
Enqueue work for the thread pool.
Definition: ThreadPool.hpp:110