mason/src2/taskmanager.h
2023-09-25 17:15:24 -03:00

44 lines
1009 B
C++

#pragma once
#include <string>
#include <queue>
#include <vector>
#include <thread>
#include <mutex>
#include <condition_variable>
#include <functional>
#include <optional>
#include <exception>
class TaskManager {
public:
using Error = std::optional<const std::exception*>;
using Job = std::function<void ()>;
using Result = std::function<void (Error)>;
using Task = std::pair<Job, std::optional<Result>>;
TaskManager();
~TaskManager();
void start();
void stop();
void wait() const;
void queue(const Job& job);
void queue(const Job& job, const Result& result);
bool busy() const;
private:
void loop();
void executeTask(const Task& task) const;
private:
bool running;
bool stopping;
uint32_t maxThreads;
uint32_t activeThreads;
std::queue<Task> tasks;
mutable std::mutex mutex;
mutable std::condition_variable loopConditional;
mutable std::condition_variable waitConditional;
std::vector<std::thread> threads;
};