Interview Question Interface Implementation

Could you help me with the following interview question.

This Sleep(int seconds) function implements the following interface so that timers can be used:

  • function void CreateTimer(void (*func)(), int seconds) that its purpose is to create a timer
  • function void StartTimers() that its purpose is to start all timers

Each running timer should be delayed for a few seconds, and then use the callback to call the function. Example:

 CreateTimer(func1,3); CreateTimer(func2,7); CreateTimer(func3,10); StartTimers() 

The following should happen:

Delay for 3 seconds, then calling function 1. Delay for 4 seconds, and then calling function 2. Delay for 3 seconds, and then calling function 3.

The question is how to implement such an interface?

+6
source share
3 answers

EDIT 1: Use the questions API.

EDIT 2: Unfortunately, did not call q.pop ();

This sounds like a job for std::priority_queue , sorted by date.

 //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(); } } 
+3
source

The psuedo code may be something like>

  • Create a global type dictionary
  • In timer creation mode, add two parameters to the dictionary
  • In the start timer function, call each of the functions after their value in the dictionary is asleep
+1
source
 //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]; } } 
+1
source

Source: https://habr.com/ru/post/887488/


All Articles