Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Interview question interface implementation

Tags:

c++

interface

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 function 2. Delay for 3 seconds and then call for function 3.

The question is how implement such interface?

like image 302
Yakov Avatar asked May 06 '11 22:05

Yakov


People also ask

What is the correct way to implement an 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.

Which is the valid example of interfaces implementation?

Explanation: Concrete class implements an interface.

What is interface how it is implemented explain with suitable example?

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".


1 Answers

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();
  }
}
like image 177
Robᵩ Avatar answered Sep 28 '22 03:09

Robᵩ