Thread and Routine Manager
Source Code
class Framework_TaskManager {
public:
// Class construction
Framework_TaskManager() : Task_Manager_TerminationCall(false) {}
// Deconstruction
~Framework_TaskManager() {
Terminate();
}
// Add newer tasks, note: this is a vector of tasks, again, not an array. fuck.
// Also: Adding task can run every cycle for said amount. For example, run every 5 seconds
void AddTask(std::function<void()> task, std::chrono::seconds interval) {
Tasks.emplace_back(std::move(task), interval);
}
// Start the task and thread
// this will start the thread and the task and will properly execute
void Start() {
if (!thread.joinable()) {
thread = std::thread(&Framework_TaskManager::Task_Manager_ExecutionThreadStep, this);
}
}
// Terminate or remove the thread
void Terminate() {
{
std::lock_guard<std::mutex> lock(MutX);
Task_Manager_TerminationCall = true;
}
ConditonalVar.notify_all();
if (thread.joinable()) {
thread.join();
}
}
private:
// Since we are adding tasks and ensuring that tasks are secure
// we want to create a structure to define tasks which will include
// a function and the time in which the task is executed.
struct Task {
std::function<void()> task;
std::chrono::seconds interval;
std::chrono::steady_clock::time_point nextRun;
Task(
std::function<void()> t, std::chrono::seconds i)
: task(
std::move(t)),
interval(i),
nextRun(std::chrono::steady_clock::now() + i) {}
};
std::vector<Task> Tasks;
std::mutex MutX;
std::condition_variable ConditonalVar;
bool Task_Manager_TerminationCall;
std::thread thread;
void Task_Manager_ExecutionThreadStep() {
std::unique_lock<std::mutex> lock(MutX);
while (!Task_Manager_TerminationCall) {
ConditonalVar.wait_until(
lock,
Tasks.front().nextRun,
[this] {
return Task_Manager_TerminationCall || std::chrono::steady_clock::now() >= Tasks.front().nextRun;
}
);
if (!Task_Manager_TerminationCall) {
for (auto& task : Tasks) {
task.task();
task.nextRun = std::chrono::steady_clock::now() + task.interval;
}
}
}
}
};Use of the class
Last updated
