|
| 1 | +#pragma once |
| 2 | + |
| 3 | +#include <atomic> |
| 4 | +#include <condition_variable> |
| 5 | +#include <functional> |
| 6 | +#include <future> |
| 7 | +#include <memory> |
| 8 | +#include <mutex> |
| 9 | +#include <queue> |
| 10 | +#include <thread> |
| 11 | +#include <vector> |
| 12 | + |
| 13 | +#include "executor.h" |
| 14 | +#include "koroutine/debug.h" |
| 15 | + |
| 16 | +namespace koroutine { |
| 17 | + |
| 18 | +/** |
| 19 | + * @brief A multi-threaded executor with a thread pool and delayed task support. |
| 20 | + * |
| 21 | + * Features: |
| 22 | + * - Fixed size thread pool for immediate task execution. |
| 23 | + * - Dedicated timer thread for handling delayed tasks efficiently. |
| 24 | + * - Graceful shutdown mechanism. |
| 25 | + * - Thread-safe task submission. |
| 26 | + */ |
| 27 | +class ThreadPoolExecutor : public AbstractExecutor { |
| 28 | + public: |
| 29 | + /** |
| 30 | + * @brief Construct a new Thread Pool Executor |
| 31 | + * |
| 32 | + * @param threads Number of worker threads. Defaults to hardware concurrency. |
| 33 | + */ |
| 34 | + explicit ThreadPoolExecutor( |
| 35 | + size_t threads = std::thread::hardware_concurrency()) |
| 36 | + : stop_(false) { |
| 37 | + if (threads == 0) threads = 1; |
| 38 | + |
| 39 | + LOG_INFO("ThreadPoolExecutor: Starting with ", threads, " threads"); |
| 40 | + |
| 41 | + // Start worker threads |
| 42 | + for (size_t i = 0; i < threads; ++i) { |
| 43 | + workers_.emplace_back([this, i] { |
| 44 | + (void)i; // Suppress unused warning if logging is disabled |
| 45 | + LOG_TRACE("ThreadPoolExecutor: Worker ", i, " started"); |
| 46 | + while (true) { |
| 47 | + std::function<void()> task; |
| 48 | + { |
| 49 | + std::unique_lock<std::mutex> lock(this->queue_mutex_); |
| 50 | + this->condition_.wait( |
| 51 | + lock, [this] { return this->stop_ || !this->tasks_.empty(); }); |
| 52 | + |
| 53 | + if (this->stop_ && this->tasks_.empty()) { |
| 54 | + LOG_TRACE("ThreadPoolExecutor: Worker ", i, " stopping"); |
| 55 | + return; |
| 56 | + } |
| 57 | + |
| 58 | + task = std::move(this->tasks_.front()); |
| 59 | + this->tasks_.pop(); |
| 60 | + } |
| 61 | + try { |
| 62 | + task(); |
| 63 | + } catch (const std::exception& e) { |
| 64 | + LOG_ERROR("ThreadPoolExecutor: Task threw exception: ", e.what()); |
| 65 | + } catch (...) { |
| 66 | + LOG_ERROR("ThreadPoolExecutor: Task threw unknown exception"); |
| 67 | + } |
| 68 | + } |
| 69 | + }); |
| 70 | + } |
| 71 | + |
| 72 | + // Start timer thread for delayed tasks |
| 73 | + timer_thread_ = std::thread([this] { |
| 74 | + LOG_TRACE("ThreadPoolExecutor: Timer thread started"); |
| 75 | + while (true) { |
| 76 | + std::unique_lock<std::mutex> lock(timer_mutex_); |
| 77 | + |
| 78 | + if (stop_ && delayed_tasks_.empty()) { |
| 79 | + LOG_TRACE("ThreadPoolExecutor: Timer thread stopping"); |
| 80 | + return; |
| 81 | + } |
| 82 | + |
| 83 | + if (delayed_tasks_.empty()) { |
| 84 | + timer_cv_.wait(lock, |
| 85 | + [this] { return stop_ || !delayed_tasks_.empty(); }); |
| 86 | + if (stop_ && delayed_tasks_.empty()) return; |
| 87 | + } |
| 88 | + |
| 89 | + // Check top task |
| 90 | + auto now = std::chrono::steady_clock::now(); |
| 91 | + // Use const_cast to move the function out before popping, as top() |
| 92 | + // returns const ref |
| 93 | + if (delayed_tasks_.top().first <= now) { |
| 94 | + auto task = std::move( |
| 95 | + const_cast<std::function<void()>&>(delayed_tasks_.top().second)); |
| 96 | + delayed_tasks_.pop(); |
| 97 | + lock.unlock(); |
| 98 | + |
| 99 | + // Submit to main thread pool |
| 100 | + execute(std::move(task)); |
| 101 | + } else { |
| 102 | + auto next_time = delayed_tasks_.top().first; |
| 103 | + timer_cv_.wait_until(lock, next_time); |
| 104 | + } |
| 105 | + } |
| 106 | + }); |
| 107 | + } |
| 108 | + |
| 109 | + ~ThreadPoolExecutor() override { shutdown(); } |
| 110 | + |
| 111 | + void execute(std::function<void()>&& func) override { |
| 112 | + { |
| 113 | + std::unique_lock<std::mutex> lock(queue_mutex_); |
| 114 | + if (stop_) { |
| 115 | + LOG_WARN("ThreadPoolExecutor: execute called on stopped executor"); |
| 116 | + return; |
| 117 | + // Alternatively throw, but logging is safer for destructors |
| 118 | + } |
| 119 | + tasks_.emplace(std::move(func)); |
| 120 | + } |
| 121 | + condition_.notify_one(); |
| 122 | + } |
| 123 | + |
| 124 | + void execute_delayed(std::function<void()>&& func, long long ms) override { |
| 125 | + auto execute_at = |
| 126 | + std::chrono::steady_clock::now() + std::chrono::milliseconds(ms); |
| 127 | + { |
| 128 | + std::unique_lock<std::mutex> lock(timer_mutex_); |
| 129 | + if (stop_) { |
| 130 | + LOG_WARN( |
| 131 | + "ThreadPoolExecutor: execute_delayed called on stopped executor"); |
| 132 | + return; |
| 133 | + } |
| 134 | + delayed_tasks_.push({execute_at, std::move(func)}); |
| 135 | + } |
| 136 | + // Notify timer thread to re-evaluate wait time (in case this task is |
| 137 | + // sooner than current top) |
| 138 | + timer_cv_.notify_one(); |
| 139 | + } |
| 140 | + |
| 141 | + void shutdown() { |
| 142 | + if (stop_.exchange(true)) return; // Already stopped |
| 143 | + |
| 144 | + LOG_INFO("ThreadPoolExecutor: Shutting down..."); |
| 145 | + |
| 146 | + // Wake up all workers |
| 147 | + { |
| 148 | + std::unique_lock<std::mutex> lock(queue_mutex_); |
| 149 | + // stop_ is already true |
| 150 | + } |
| 151 | + condition_.notify_all(); |
| 152 | + |
| 153 | + // Wake up timer thread |
| 154 | + { |
| 155 | + std::unique_lock<std::mutex> lock(timer_mutex_); |
| 156 | + // stop_ is already true |
| 157 | + } |
| 158 | + timer_cv_.notify_all(); |
| 159 | + |
| 160 | + for (std::thread& worker : workers_) { |
| 161 | + if (worker.joinable()) worker.join(); |
| 162 | + } |
| 163 | + if (timer_thread_.joinable()) timer_thread_.join(); |
| 164 | + |
| 165 | + LOG_INFO("ThreadPoolExecutor: Shutdown complete"); |
| 166 | + } |
| 167 | + |
| 168 | + private: |
| 169 | + std::vector<std::thread> workers_; |
| 170 | + std::queue<std::function<void()>> tasks_; |
| 171 | + |
| 172 | + std::mutex queue_mutex_; |
| 173 | + std::condition_variable condition_; |
| 174 | + std::atomic<bool> stop_; |
| 175 | + |
| 176 | + // Timer related |
| 177 | + using Clock = std::chrono::steady_clock; |
| 178 | + using TimePoint = Clock::time_point; |
| 179 | + using TaskPair = std::pair<TimePoint, std::function<void()>>; |
| 180 | + |
| 181 | + struct CompareTasks { |
| 182 | + bool operator()(const TaskPair& a, const TaskPair& b) const { |
| 183 | + return a.first > b.first; // Min heap based on time |
| 184 | + } |
| 185 | + }; |
| 186 | + |
| 187 | + std::priority_queue<TaskPair, std::vector<TaskPair>, CompareTasks> |
| 188 | + delayed_tasks_; |
| 189 | + std::mutex timer_mutex_; |
| 190 | + std::condition_variable timer_cv_; |
| 191 | + std::thread timer_thread_; |
| 192 | +}; |
| 193 | + |
| 194 | +} // namespace koroutine |
0 commit comments