#ifndef THREAD_POOL_H
#define THREAD_POOL_H
#include <thread>
#include <mutex>
#include <vector>
#include <queue>
#include <functional>
#include <condition_variable>
#include <shared_mutex>

#include "loging.h"

namespace zsy
{
    class ThreadPool
    {
        std::vector<std::jthread> workers; // 工作线程
        std::queue<std::function<void()> > tasks; // 任务队列
        mutable std::recursive_mutex queueMutex; // 保护任务队列的互斥锁
        std::condition_variable_any taskCondition; // 任务通知条件变量
        // 0-->不可用，1-->已启动，2-->已关闭
        uint8_t status; // 线程池停止标志
        std::shared_mutex status_mtx;

    public:
        explicit ThreadPool(size_t threadCount = std::thread::hardware_concurrency());

        template<typename Fn>
        void submit(Fn &&task) noexcept
        {
            std::shared_lock status_lock(status_mtx);
            if (status != 1)
            {
                LOGGER_ERROR("线程池未启动");
                return;
            }
            std::unique_lock lock(queueMutex);
            tasks.emplace(std::forward<Fn>(task));
            taskCondition.notify_one();
        }

        ~ThreadPool();

        ThreadPool(const ThreadPool &) = delete;

        ThreadPool &operator=(const ThreadPool &) = delete;

        ThreadPool(ThreadPool &&) = delete;

        ThreadPool &operator=(ThreadPool &&) = delete;
    };
} // zsy

#endif //THREAD_POOL_H
