| 113 | |
| 114 | template<typename T> |
| 115 | void ThreadPool<T>::manageWorkers() { |
| 116 | for (int i = 0; i < max_worker_threads_; i++) { |
| 117 | std::stringstream thread_name; |
| 118 | thread_name << name_ << " #" << i; |
| 119 | auto worker_thread = std::make_shared<WorkerThread>(thread_name.str()); |
| 120 | worker_thread->thread_ = createThread(std::bind(&ThreadPool::run_tasks, this, worker_thread)); |
| 121 | thread_queue_.push_back(worker_thread); |
| 122 | current_workers_++; |
| 123 | } |
| 124 | |
| 125 | if (daemon_threads_) { |
| 126 | for (auto &thread : thread_queue_) { |
| 127 | thread->thread_.detach(); |
| 128 | } |
| 129 | } |
| 130 | |
| 131 | if (nullptr != thread_manager_) { |
| 132 | while (running_) { |
| 133 | auto waitperiod = std::chrono::milliseconds(500); |
| 134 | { |
| 135 | std::unique_lock<std::recursive_mutex> lock(manager_mutex_, std::try_to_lock); |
| 136 | if (!lock.owns_lock()) { |
| 137 | // Threadpool is being stopped/started or config is being changed, better wait a bit |
| 138 | std::this_thread::sleep_for(std::chrono::milliseconds(10)); |
| 139 | } |
| 140 | if (thread_manager_->isAboveMax(current_workers_)) { |
| 141 | auto max = thread_manager_->getMaxConcurrentTasks(); |
| 142 | auto differential = current_workers_ - max; |
| 143 | thread_reduction_count_ += differential; |
| 144 | } else if (thread_manager_->shouldReduce()) { |
| 145 | if (current_workers_ > 1) |
| 146 | thread_reduction_count_++; |
| 147 | thread_manager_->reduce(); |
| 148 | } else if (thread_manager_->canIncrease() && max_worker_threads_ > current_workers_) { // increase slowly |
| 149 | std::unique_lock<std::mutex> lock(worker_queue_mutex_); |
| 150 | auto worker_thread = std::make_shared<WorkerThread>(); |
| 151 | worker_thread->thread_ = createThread(std::bind(&ThreadPool::run_tasks, this, worker_thread)); |
| 152 | if (daemon_threads_) { |
| 153 | worker_thread->thread_.detach(); |
| 154 | } |
| 155 | thread_queue_.push_back(worker_thread); |
| 156 | current_workers_++; |
| 157 | } |
| 158 | std::shared_ptr<WorkerThread> thread_ref; |
| 159 | while (deceased_thread_queue_.tryDequeue(thread_ref)) { |
| 160 | std::unique_lock<std::mutex> lock(worker_queue_mutex_); |
| 161 | if (thread_ref->thread_.joinable()) |
| 162 | thread_ref->thread_.join(); |
| 163 | thread_queue_.erase(std::remove(thread_queue_.begin(), thread_queue_.end(), thread_ref), thread_queue_.end()); |
| 164 | } |
| 165 | } |
| 166 | std::this_thread::sleep_for(waitperiod); |
| 167 | } |
| 168 | } else { |
| 169 | for (auto &thread : thread_queue_) { |
| 170 | if (thread->thread_.joinable()) |
| 171 | thread->thread_.join(); |
| 172 | } |
nothing calls this directly
no test coverage detected