c++ - 在 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))
}
主循环是这样的。
当需要运行的函数被提供给调度程序时,一个线程应该运行它。我将如何实现这一目标?
解决方案
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.
推荐阅读
- gatsby - 我无法在 gatsby-plugin-image 上传递道具
- sbt-native-packager - 终端中的 SBT shell 项目出现错误
- python - 错误“系列”对象没有属性“箱线图”
- azure - az webapp log tail - 跳过现有日志
- rxjs - 如果发生其他事件,则取消展开
- r - 使用复杂的调查设计对象来拟合带有 tbl_uvregression() 的单变量逻辑模型
- laravel - Laravel 模型计数不更新值
- javascript - 悬停在下一个元素或兄弟元素上时图像悬停不起作用
- android - App Auth Intent 返回 App UI 问题
- json - 格式json输出jq