#include "taskrunner.hpp"


TaskRunner::TaskRunner() : stopFlag(false) {
         try {
            worker = std::thread(&TaskRunner::run, this);
        }catch (...) {
            stopFlag = true;
            throw;
        }
}

TaskRunner::~TaskRunner() {
    {
        std::unique_lock<std::mutex> lock(mtx);
        stopFlag = true;
    }
    cv.notify_all();  // 唤醒线程准备退出
    if (worker.joinable()) {
        worker.join();
    }
}


void TaskRunner::addTask(const std::function<void()>& task) {
        {
            std::unique_lock<std::mutex> lock(mtx);
            tasks.push(task);
        }
        cv.notify_one();
}

void TaskRunner::run() {
    while (true) {
        std::function<void()> task;

        {
            std::unique_lock<std::mutex> lock(mtx);
            cv.wait(lock, [this]() { return stopFlag || !tasks.empty(); });

            if (stopFlag && tasks.empty()) {
                break; // 退出线程
            }

            task = tasks.front();
            tasks.pop();
        }

        // 执行任务
        task();
    }
}