/
AirLexa
/
06
Обзор
Документация
Войти
/
AirLexa
/
06
Код
Запросы
0
Задачи
Вики
Пакеты
0
Релизы
0
CI/CD
Аналитика
Безопасность
master
Lesson_06/SafeQueue/thread_pool.h
101 строка
3 KB
AirLexa
курсовая
19 июн 2026, 14:48
Верифицирован
19 июн 2026, 14:48
d9b94c2
Код
Авторство
О чём код?
#pragma once #include "safe_queue.h" #include <vector> #include <thread> #include <functional> #include <future> #include <memory> class thread_pool { public: explicit thread_pool(size_t thread_count = std::thread::hardware_concurrency()) { if (thread_count == 0) { thread_count = 1; } workers_.reserve(thread_count); for (size_t i = 0; i < thread_count; ++i) { workers_.emplace_back(&thread_pool::work, this); } } ~thread_pool() { // Останавливаем очередь — все ожидающие в pop() потоки проснутся tasks_.shutdown(); for (auto& t : workers_) { if (t.joinable()) { t.join(); } } } thread_pool(const thread_pool&) = delete; thread_pool& operator=(const thread_pool&) = delete; // Помещает задачу без значения результата (std::function<void()>) void submit(std::function<void()> task) { tasks_.push(std::move(task)); } // Помещает задачу с возможностью получить результат через future template <typename F, typename... Args> auto submit_task(F&& f, Args&&... args) -> std::future<std::invoke_result_t<F, Args...>> { using return_type = std::invoke_result_t<F, Args...>; auto task_ptr = std::make_shared<std::packaged_task<return_type()>>(std::bind(std::forward<F>(f), std::forward<Args>(args)...)); std::future<return_type> result = task_ptr->get_future(); tasks_.push([task_ptr]() { (*task_ptr)(); }); return result; } size_t thread_count() const { return workers_.size(); } size_t pending_tasks() const { return tasks_.size(); } private: // Метод, выполняемый каждым рабочим потоком: забирает задачу из очереди, исполняет её, затем снова проверяет очередь — и так до завершения работы пула. void work() { while (true) { std::function<void()> task; if (!tasks_.pop(task)) { // Очередь остановлена и пуста — завершаем поток break; } if (task) { task(); } } } std::vector<std::thread> workers_; safe_queue<std::function<void()>> tasks_; };