1 #ifndef CAFFE2_UTILS_THREAD_POOL_H_ 2 #define CAFFE2_UTILS_THREAD_POOL_H_ 4 #include <condition_variable> 12 std::queue< std::function< void() > > tasks_;
13 std::vector<std::thread> threads_;
15 std::condition_variable condition_;
16 std::condition_variable completed_;
19 std::size_t available_;
25 : threads_(pool_size), running_(true), complete_(true),
26 available_(pool_size), total_(pool_size) {
27 for ( std::size_t i = 0; i < pool_size; ++i ) {
28 threads_[i] = std::thread(
29 std::bind(&TaskThreadPool::main_loop,
this));
37 std::unique_lock< std::mutex > lock(mutex_);
39 condition_.notify_all();
43 for (
auto& t : threads_) {
48 catch (
const std::exception&) {}
52 template <
typename Task>
54 std::unique_lock<std::mutex> lock(mutex_);
58 tasks_.push(std::function<
void()>(task));
60 condition_.notify_one();
65 std::unique_lock<std::mutex> lock(mutex_);
67 completed_.wait(lock);
76 std::unique_lock<std::mutex> lock(mutex_);
77 while (tasks_.empty() && running_) {
78 condition_.wait(lock);
89 std::function< void() > task = tasks_.front();
101 catch (
const std::exception& ) {}
109 if (tasks_.empty() && available_ == total_) {
111 completed_.notify_one();
void runTask(Task task)
Add task to the thread pool if a thread is currently available.
void waitWorkComplete()
Wait for queue to be empty.
~TaskThreadPool()
Destructor.
TaskThreadPool(std::size_t pool_size)
Constructor.