#include "thread_pool.hpp" ThreadPool::ThreadPool(size_t num_threads) { states = new bool[num_threads]({ false }); for (auto i = 0; i < num_threads; ++i) { threads.emplace_back([this, i] { while (true) { std::function task; std::unique_lock lock(mutex); cv.wait(lock, [this] { return !tasks.empty() || stop; }); if (tasks.empty() || stop) { return; } states[i] = true; task = std::move(tasks.front()); tasks.pop(); lock.unlock(); task(); states[i] = false; } }); } } ThreadPool::~ThreadPool() { std::unique_lock lock(mutex); stop = true; lock.unlock(); cv.notify_all(); for (auto& thread : threads) { thread.join(); } } void ThreadPool::add(std::function task) { std::unique_lock lock(mutex); tasks.emplace(std::move(task)); cv.notify_one(); lock.unlock(); } uint32_t ThreadPool::size() { return tasks.size(); } bool ThreadPool::isWorking() { for (auto i = 0; i < threads.size(); i++) { if (states[i]) { return true; } } return false; }