|
| 1 | +#include "ThreadPool.h" |
| 2 | + |
| 3 | +#include "Utils.h" |
| 4 | + |
| 5 | +using namespace processor; |
| 6 | +using namespace commons; |
| 7 | + |
| 8 | +// ------------------------------------------------------------------------------------------------- |
| 9 | +// Public methods |
| 10 | + |
| 11 | +ThreadPool::ThreadPool(const string& id, unsigned int num_threads) : Processor(id) { |
| 12 | + this->num_threads = num_threads; |
| 13 | + this->active_tasks = 0; |
| 14 | +} |
| 15 | + |
| 16 | +ThreadPool::~ThreadPool() {} |
| 17 | + |
| 18 | +void ThreadPool::setup() { Processor::setup(); } |
| 19 | + |
| 20 | +void ThreadPool::start() { |
| 21 | + for (unsigned int i = 0; i < this->num_threads; ++i) { |
| 22 | + this->workers.emplace_back([this, i] { |
| 23 | + while (true) { |
| 24 | + function<void()> task; |
| 25 | + { |
| 26 | + unique_lock<mutex> lock(this->queue_mutex); |
| 27 | + this->condition.wait(lock, |
| 28 | + [this] { return this->stop_flag || !this->tasks.empty(); }); |
| 29 | + if (this->stop_flag && this->tasks.empty()) return; |
| 30 | + |
| 31 | + task = move(this->tasks.front()); |
| 32 | + this->tasks.pop(); |
| 33 | + ++this->active_tasks; |
| 34 | + } |
| 35 | + task(); |
| 36 | + { |
| 37 | + unique_lock<mutex> lock(this->queue_mutex); |
| 38 | + --this->active_tasks; |
| 39 | + if (this->tasks.empty() && this->active_tasks == 0) { |
| 40 | + this->done_condition.notify_all(); |
| 41 | + } |
| 42 | + } |
| 43 | + } |
| 44 | + }); |
| 45 | + } |
| 46 | + Processor::start(); |
| 47 | +} |
| 48 | + |
| 49 | +void ThreadPool::stop() { |
| 50 | + { |
| 51 | + unique_lock<mutex> lock(queue_mutex); |
| 52 | + this->stop_flag = true; |
| 53 | + } |
| 54 | + condition.notify_all(); |
| 55 | + for (thread& worker : workers) worker.join(); |
| 56 | + Processor::stop(); |
| 57 | +} |
| 58 | + |
| 59 | +void ThreadPool::enqueue(function<void()> task) { |
| 60 | + if (is_running()) { |
| 61 | + { |
| 62 | + unique_lock<mutex> lock(queue_mutex); |
| 63 | + tasks.emplace(move(task)); |
| 64 | + } |
| 65 | + condition.notify_one(); |
| 66 | + } else { |
| 67 | + Utils::error("Attempt to add a job to ThreadPool " + this->to_string() + |
| 68 | + " which has not being started"); |
| 69 | + } |
| 70 | +} |
| 71 | + |
| 72 | +int ThreadPool::size() { |
| 73 | + unique_lock<mutex> lock(queue_mutex); |
| 74 | + return tasks.size(); |
| 75 | +} |
| 76 | + |
| 77 | +bool ThreadPool::empty() { |
| 78 | + unique_lock<mutex> lock(queue_mutex); |
| 79 | + return tasks.empty(); |
| 80 | +} |
| 81 | + |
| 82 | +void ThreadPool::wait() { |
| 83 | + unique_lock<mutex> lock(queue_mutex); |
| 84 | + done_condition.wait(lock, [this] { return tasks.empty() && active_tasks == 0; }); |
| 85 | +} |
0 commit comments