#include "thread_pool.h"

#include "loging.h"

namespace zsy
{
    ThreadPool::ThreadPool(size_t threadCount):status(0)
    {
        if (threadCount < 1) threadCount = 1;
        workers.reserve(threadCount);

        for (size_t i = 0; i < threadCount; ++i)
        {
            workers.emplace_back([this](const std::stop_token &st)

            {
                while (!st.stop_requested())
                {
                    {
                        std::unique_lock lock(queueMutex);
                        taskCondition.wait(lock, st, [this]
                        {
                            return !tasks.empty();
                        });

                        if (st.stop_requested() && tasks.empty())
                        {
                            LOGGER_INFO("已停止线程");
                            return;
                        }
                        std::function<void()> &task = tasks.front();

                        try
                        {
                            if (task) task();
                        } catch (const std::exception &e)
                        {
                            LOGGER_ERROR("任务执行失败: {}", e.what());
                        }
                        catch (...)
                        {
                            LOGGER_ERROR("未知异常，任务执行失败");
                        }

                        tasks.pop();
                    }
                }
            });
        }
        status = 1;
    }

    ThreadPool::~ThreadPool()
    {
        std::unique_lock lock(status_mtx);
        status = 2;
        LOGGER_INFO("正在销毁线程池...");
        workers.clear();
        LOGGER_INFO("线程池已销毁");
    }
} // zsy
