开发者

Interview question interface implementation

Could your please help me with following interview question.

Given function ‪Sleep(int seconds) implement following interface so timers could be used:

  • function ‪void CreateTimer(void (*func)(), int seconds) that her purpose is to create timer
  • function ‫‪void StartTimers() that her purpose to start all the timers

Every 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 funct开发者_StackOverflow中文版ion 2. Delay for 3 seconds and then call for function 3.

The question is how implement such interface?


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();
  }
}


The psuedo code could be something like >

  1. Create a global dictionary of type
  2. In create timer function, keep adding the two parameters in the dictionary
  3. In start timer function, call each of the funcs after a Sleep of their respective value in the dictionary


//globals vector v1; vector v2;

CreateTimer(func, delay) {  
v1.push_back(func);  
v2.push_back(delay); }


StartTimers() {   startDelay=0;  
for(i=0; i<v2.size; i++)   {
    sleep(v2[i]-startDelay);
    *v1[i]   //call the function
    startDelay=v2[i];   }

}
0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜