如何实现C++任务调度器
How to implement C++ Task Scheduler
我知道下面的代码可能不是Task Scheduler
不过,想得到您对理解调度器的宝贵意见
我正在尝试理解并想出一个可以称为 TaskScheduler 的最低限度代码。
我有以下代码,但不确定它是否足以作为调度。
有人可以提供评论和代码框架参考或链接吗?
谢谢!!
#include <iostream>
#include <thread>
#include <future>
#include <queue>
#include <mutex>
#include <condition_variable>
using namespace std;
int factorial_loc(int val) {
int res = 1;
while(val>0) {
res *= val;
val--;
}
return res;
}
queue<packaged_task<int()>> q;
mutex mtx;
condition_variable cond;
void thread_1() {
unique_lock<mutex> ul(mtx);
cond.wait(ul, [](){
return !q.empty();
});
auto f = std::move(q.front());
q.pop();
f();
}
void run_packaged_task()
{
packaged_task<int(int)> t(factorial_loc);
packaged_task<int()> t2(std::bind(factorial_loc, 4));
future<int> f = t2.get_future();
thread t1(thread_1);
{
unique_lock<mutex> ul(mtx);
q.push(std::move(t2));
}
cond.notify_one();
cout<<"\n Res: "<<f.get();
t1.join();
}
I have the following code but am not sure if it suffices as scheduling.
为什么不这样做呢?
void run_packaged_task()
{
cout << "\n Res: " << factorial_loc(4);
}
也许您认为我的 run_packaged_task()
版本不是调度程序。嗯,好的。我也不这么认为。但是,就来电者而言,我的版本与您的版本完全一样;
- 它计算 4 的阶乘,
- 它将结果写入
cout
,
- 然后,只有在完成后,returns。
您的代码包含一些调度程序;线程、队列、表示任务的数据类型,但您不会使用这些部分中的任何一个来执行任何看起来像调度的事情。
IMO,您需要考虑“调度程序”的含义。 您希望调度程序做什么?
调度程序是否应该尽快执行每个任务?或者,如果没有,那么什么时候?来电者怎么说什么时候?调度程序如何将任务的执行推迟到这样的时间?
调用者是否必须等到任务完成?呼叫者是否应该选择等待?
我不太清楚您所说的“调度程序”是什么意思,但如果我的猜测是正确的,那么它与 thread pool 会有一些共同点。如果您首先搜索如何实现简单线程池的示例,然后考虑如何“改进”它以制作“调度程序”,也许您可以获得一些牵引力。
我知道下面的代码可能不是Task Scheduler 不过,想得到您对理解调度器的宝贵意见
我正在尝试理解并想出一个可以称为 TaskScheduler 的最低限度代码。 我有以下代码,但不确定它是否足以作为调度。 有人可以提供评论和代码框架参考或链接吗?
谢谢!!
#include <iostream>
#include <thread>
#include <future>
#include <queue>
#include <mutex>
#include <condition_variable>
using namespace std;
int factorial_loc(int val) {
int res = 1;
while(val>0) {
res *= val;
val--;
}
return res;
}
queue<packaged_task<int()>> q;
mutex mtx;
condition_variable cond;
void thread_1() {
unique_lock<mutex> ul(mtx);
cond.wait(ul, [](){
return !q.empty();
});
auto f = std::move(q.front());
q.pop();
f();
}
void run_packaged_task()
{
packaged_task<int(int)> t(factorial_loc);
packaged_task<int()> t2(std::bind(factorial_loc, 4));
future<int> f = t2.get_future();
thread t1(thread_1);
{
unique_lock<mutex> ul(mtx);
q.push(std::move(t2));
}
cond.notify_one();
cout<<"\n Res: "<<f.get();
t1.join();
}
I have the following code but am not sure if it suffices as scheduling.
为什么不这样做呢?
void run_packaged_task()
{
cout << "\n Res: " << factorial_loc(4);
}
也许您认为我的 run_packaged_task()
版本不是调度程序。嗯,好的。我也不这么认为。但是,就来电者而言,我的版本与您的版本完全一样;
- 它计算 4 的阶乘,
- 它将结果写入
cout
, - 然后,只有在完成后,returns。
您的代码包含一些调度程序;线程、队列、表示任务的数据类型,但您不会使用这些部分中的任何一个来执行任何看起来像调度的事情。
IMO,您需要考虑“调度程序”的含义。 您希望调度程序做什么?
调度程序是否应该尽快执行每个任务?或者,如果没有,那么什么时候?来电者怎么说什么时候?调度程序如何将任务的执行推迟到这样的时间?
调用者是否必须等到任务完成?呼叫者是否应该选择等待?
我不太清楚您所说的“调度程序”是什么意思,但如果我的猜测是正确的,那么它与 thread pool 会有一些共同点。如果您首先搜索如何实现简单线程池的示例,然后考虑如何“改进”它以制作“调度程序”,也许您可以获得一些牵引力。