views:

151

answers:

1

Let's say there is an imaginary operating system...

There is a function in it called settime that gets a pointer to function and a timestamp.

The catch is that every time the function is called it runs over the last call (so only the new function being provided as parameter will be called).

I want to expose a new function to my users called settime2, which will allow users to call it, and time a function without destroying the previous calls.

In the settime2 implementation I can call settime. and getcurrenttime. and even call settime with settime or settime2 as the function pointer argument.

Any advice?

thanks

+2  A: 

Working under the assumption that the function that gets called is called at a specific time...

What settime2 needs to do is keep a linked list of function pointers and timestamp values. Insert a new function/timestamp value into the list in sorted order: earliest first.

Use settime to set up a generic handler function and set the timeout to the earliest time required (the head of the timeout list).

When the generic handler is called, remove the head of the list and call its function. Do this repeatedly if the head of the list has the same timestamp.

If the list is not empty, call settime again with the timestamp at the head of the list.

If the timestamp is really a duration (e.g. 10msec), do almost the same thing but have the saved durations be the sum of the all the previous durations and a delta to form the last duration.

For example, three calls, with (f,15), (g,7), (h, 7), and (i,20) would make the list

head -> (g,7) -> (h,0) -> (f, 8) -> (i,5)

The first settime would be at 7 and g and h would get called. the next settime would be 8 after that (a total of 15) and f called, and finally after 5 more (at 20) i would be called.

Be careful to handle the list changing when it is active. ;-)

Richard Pennington
If the number of functions is very large a list will be a pretty inefficient data structure. It does have the advantage that most libraries have direct support for it though. If it's important to you you might want to look into using a heap to store the function pointers and their associated times.
Omnifarious