#include "IoContextPool.h"

IoContextPool::IoContextPool(size_t pool_size) {
    if (pool_size == 0) pool_size = 1;  // 确保至少有一个线程

    for (size_t i = 0; i < pool_size; ++i) {
        auto io_ctx = std::make_shared<asio::io_context>();
        io_contexts_.emplace_back(io_ctx);
        work_guards_.emplace_back(std::make_unique<asio::executor_work_guard<asio::io_context::executor_type>>(asio::make_work_guard(*io_ctx)));
    }
}

IoContextPool::~IoContextPool() {
    stop();
}

void IoContextPool::start() {
    for (auto& io_ctx : io_contexts_) {
        worker_threads_.emplace_back([io_ctx] {
            io_ctx->run();
        });
    }
}

void IoContextPool::stop() {
    for (auto& io_ctx : io_contexts_) {
        io_ctx->stop();
    }

    for (auto& t : worker_threads_) {
        if (t.joinable()) t.join();
    }

    work_guards_.clear();
}

asio::io_context& IoContextPool::getIoContext() {
    // 轮询获取下一个 io_context
    return *io_contexts_[next_io_context_.fetch_add(1) % io_contexts_.size()];
}
