space-game001/src/utils/TaskManager.h
2026-01-09 15:24:01 +03:00

43 lines
1.3 KiB
C++

#pragma once
#include <boost/asio.hpp>
#include <functional>
#include <vector>
#include <thread>
#include <memory>
namespace ZL {
class TaskManager {
private:
boost::asio::io_context ioContext;
std::unique_ptr<boost::asio::executor_work_guard<boost::asio::io_context::executor_type>> workGuard;
std::vector<std::thread> workers;
public:
//TaskManager(size_t threadCount = std::thread::hardware_concurrency()) {
TaskManager(size_t threadCount = 2) {
workGuard = std::make_unique<boost::asio::executor_work_guard<boost::asio::io_context::executor_type>>(ioContext.get_executor());
for (size_t i = 0; i < threadCount; ++i) {
workers.emplace_back([this]() {
ioContext.run();
});
}
}
// Ìåòîä äëÿ äîáàâëåíèÿ ôîíîâîé çàäà÷è
void EnqueueBackgroundTask(std::function<void()> task) {
boost::asio::post(ioContext, task);
}
// Graceful shutdown
~TaskManager() {
workGuard.reset(); // Ðàçðåøàåì ioContext.run() çàâåðøèòüñÿ, êîãäà çàäà÷ íå îñòàíåòñÿ
ioContext.stop(); // Îïöèîíàëüíî: íåìåäëåííàÿ îñòàíîâêà
for (auto& t : workers) {
if (t.joinable()) t.join();
}
}
};
} // namespace ZL