Could your please help me with following interview question.
Given function Sleep(int seconds)
implement following interface so timers could be used:
void CreateTimer(void (*func)(), int seconds)
that her purpose is to create timervoid StartTimers()
that her purpose to start all the timersEvery timer that started should delay for several seconds and then use a callback to call a function. Example:
CreateTimer(func1,3);
CreateTimer(func2,7);
CreateTimer(func3,10);
StartTimers()
The folowing should be happening:
Delay for 3 seconds and then call for function 1. Delay for 4 seconds and then call for function 2. Delay for 3 seconds and then call for function 3.
The question is how implement such interface?
To declare a class that implements an interface, you include an implements clause in the class declaration. Your class can implement more than one interface, so the implements keyword is followed by a comma-separated list of the interfaces implemented by the class.
Explanation: Concrete class implements an interface.
An interface is a description of the actions that an object can do... for example when you flip a light switch, the light goes on, you don't care how, just that it does. In Object Oriented Programming, an Interface is a description of all functions that an object must have in order to be an "X".
EDIT 1: Use the questions API.
EDIT 2: Oops, didn't call q.pop();
This sounds like a job for std::priority_queue
, ordered by deadline.
//pseudo-code
class Job;
std::priority_queue<Job, std::vector<Job>, CompareLessByDeadline> q;
CreateTimer(func, deadline) {
q.push(Job(func, deadline));
}
StartTimers() {
now = 0;
while(!q.empty()) {
Job& j = q.top();
Sleep(j.deadline-now);
now = j.deadline;
j.function();
q.pop();
}
}
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With