首页 > 解决方案 > 在 c++2a 标准中制作基于 linux 的调度功能

问题描述

我有一个函数可以不断检查是否需要安排作业...当确实需要安排作业时,我希望能够像这样调用该函数:scheduler.schedule(function(arg of function), timestamp of when to run it))这意味着该函数不需要尽快运行作为它的计划,但它将被赋予一个 EPOCH UNIX 时间戳,以知道在计划之后何时运行它。

while (sublist.size() - 1 > checked) {
    std::vector<std::string> u_time_split = Misc::split_string(sublist[checked]);

    /* if the timestamp is greater than 5 minutes away, schedule a thread with the timestamp */
    int epoch = time(0);

    if (std::stoi(u_time_split[1]) - epoch < 2) {
       std::cout << "Scheduling Thread to run using this: " << u_time_split[0] << " | When to run: " << Misc::epoch_to_utc(u_time_split[1]) << std::endl;

       schedule here
    }

    std::this_thread::sleep_for(std::chrono::seconds(5))
}

主循环是这样的。
当需要运行的函数被提供给调度程序时,一个线程应该运行它。我将如何实现这一目标?

标签: c++scheduled-tasksc++20

解决方案


Maintain a priority queue of tasks to run and one or more threads in a task running pool.

Guard the priority queue with a mutrx and a condition variable.

When a task is submitted that moves the front of the priority queue up, kick the condition variable with a notification to wake up the worker thread(s).

The worker thread(s) sleep for a timeout, or for the front of the queue's scheduled time "moving up", on the condition variable. If they wake up they check if the front of the queue is scheduled to run; if so, they do so. If not, they check if they need to update their timeout, and do so if needed.

It is a bit tricky to get it to work. I'd advise practicing by making a non-schedualing thread pool first.

The worker and submitting thread can be the same thread if you write it correctly.


推荐阅读