/** * @file thread_pool.hpp * @brief thread pool * @author DeepRobotics * @version 1.0 * @date 2026-01-07 * * @copyright Copyright (c) 2025 DeepRobotics * */ #pragma once #include #include #include #include #include #include #include class ThreadPool { public: ThreadPool(size_t numThreads) : stop(false) { for (size_t i = 0; i < numThreads; ++i) { workers.emplace_back([this]() { while (true) { std::function task; { std::unique_lock lock(this->queueMutex); this->condition.wait(lock, [this] { return this->stop || !this->tasks.empty(); }); if (this->stop && this->tasks.empty()) return; task = std::move(this->tasks.front()); this->tasks.pop(); } task(); } }); } } ~ThreadPool() { { std::unique_lock lock(queueMutex); stop = true; } condition.notify_all(); for (std::thread& worker : workers) worker.join(); } void enqueue(std::function task) { { std::unique_lock lock(queueMutex); tasks.emplace(task); } condition.notify_one(); } private: std::vector workers; std::queue> tasks; std::mutex queueMutex; std::condition_variable condition; std::atomic stop; };