I Know the following code is not Task Scheduler Perhaps However, trying to get your valuable comments in understanding the scheduler
I am trying to understand & come up with a bare minimum code which can be called as TaskScheduler. I have the following code but am not sure if it suffices as scheduling. Could someone provide the comments & code skeleton reference or links?
Thanks!!
#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();
}
CodePudding user response:
I have the following code but am not sure if it suffices as scheduling.
Why not just do this?
void run_packaged_task()
{
cout << "\n Res: " << factorial_loc(4);
}
Maybe you think that my version of run_packaged_task()
is not a scheduler. Well, OK. I don't think so either. But, as far as the caller can tell, my version does exactly the same as what your version does;
- It computes the factorial of 4,
- It writes the result to
cout
, - And then, only when that's done, it returns.
Your code contains some of the pieces of a scheduler; a thread, a queue, a data type that represents a task, but you don't use any of those pieces to do anything that looks like scheduling.
IMO, you need to think about what "scheduler" means. What do you expect a scheduler to do?
Should a scheduler execute each task as soon as possible? Or, if not, then when? How does the caller say when? How does the scheduler defer execution of the task until such time?
Should the caller have to wait until the task is completed? Should the caller have an option to wait?
I don't know exactly what you mean by "scheduler," but if my guess is correct, then it would have somewhat in common with a thread pool. Maybe you could get some traction if you start by searching for examples of how to implement a simplistic thread pool, and then think about how you could "improve" it to make a "scheduler."