diff --git a/include/echoion/core/CommandManager.hpp b/include/echoion/core/CommandManager.hpp index 483f64b..3527f12 100644 --- a/include/echoion/core/CommandManager.hpp +++ b/include/echoion/core/CommandManager.hpp @@ -4,7 +4,9 @@ #include #include #include +#include #include +#include #include #include #include @@ -174,13 +176,11 @@ namespace Echoion::Core }; void startThreadPool(); - void processCommandQueue(); void executeCommandAsync(CommandTask task); - std::vector workerThreads_; - std::queue commandQueue_; - std::mutex queueMutex_; - std::condition_variable queueCv_; + // Void worker pool backing async command execution (drains + // in-flight commands on shutdown via ~ThreadPool). + std::unique_ptr pool_; std::atomic shutdown_{false}; static constexpr size_t THREAD_POOL_SIZE = 4; // Handle up to 4 concurrent commands diff --git a/src/CommandManager.cpp b/src/CommandManager.cpp index fe6669c..e1c243e 100644 --- a/src/CommandManager.cpp +++ b/src/CommandManager.cpp @@ -119,53 +119,20 @@ namespace Echoion::Core void CommandManager::shutdown() { - { - std::lock_guard lock(queueMutex_); - shutdown_ = true; - } - queueCv_.notify_all(); - - for (auto& thread : workerThreads_) { - if (thread.joinable()) { - thread.join(); - } - } - workerThreads_.clear(); + shutdown_ = true; + // ~ThreadPool drains queued commands and joins its workers. + pool_.reset(); } void CommandManager::startThreadPool() { - for (size_t i = 0; i < THREAD_POOL_SIZE; ++i) { - workerThreads_.emplace_back([this]() { processCommandQueue(); }); - } + pool_ = + std::make_unique(THREAD_POOL_SIZE); ECHOION_LOG_INFO( std::format("CommandManager thread pool started with {} workers", THREAD_POOL_SIZE)); } - void CommandManager::processCommandQueue() - { - while (true) { - CommandTask task; - { - std::unique_lock lock(queueMutex_); - queueCv_.wait(lock, [this] { - return shutdown_ || !commandQueue_.empty(); - }); - - if (shutdown_ && commandQueue_.empty()) { - return; - } - - task = std::move(commandQueue_.front()); - commandQueue_.pop(); - } - - // Execute the command - executeCommandAsync(std::move(task)); - } - } - void CommandManager::executeCommandAsync(CommandTask task) { try { @@ -288,21 +255,19 @@ namespace Echoion::Core return true; // Command was found but not allowed } - // Queue the command for async execution + // Submit the command for async execution on the worker pool. + if (shutdown_ || !pool_) { + return false; + } CommandTask task{.clientId = clientId, .message = std::string(message), .musicManager = musicManager, .replyFunc = std::move(replyFunc), .invokerName = std::string(invokerName)}; - { - std::lock_guard lock(queueMutex_); - if (shutdown_) { - return false; - } - commandQueue_.push(std::move(task)); - } - queueCv_.notify_one(); + pool_->submit([this, task = std::move(task)]() mutable { + executeCommandAsync(std::move(task)); + }); return true; }