View Single Post
Old Sep 6th, 2007, 2:38 PM   #10
lectricpharaoh
Caffeinated Neural Net
 
lectricpharaoh's Avatar
 
Join Date: Jun 2005
Location: Dry west coast of Canada
Posts: 922
Rep Power: 4 lectricpharaoh will become famous soon enough
You need to decide which approach you want to take. I've suggested two, the first storing due times (I prefer this approach, as it is simpler and thus less likely to be buggy) and the second storing delays (as in your original post) coupled with an adjustment of those delays. From your post above, it seems you're back to the second approach. While it can work, it's got issues that can catch you out. Here's an example, starting with an empty queue:

Enqueue event A with delay 10. Queue looks like A(10). Enqueue B with delay 5. Queue is B(5) A(10). Five 'ticks' (tick being a unit of time, whether seconds, milliseconds, etc is irrelevant) pass, the timer fires, and event B is handled. By subtracting B's delay from A, we get 5, and thus we set the timer to fire after 5 ticks. We also add event C with delay 4. What happens? If we put it at the front of the queue, adjust the delay, and reset the timer, it will fire immediately (rather than after four ticks). If we stick it at the end of the queue, and let it fire along with event A, it will fire one tick later than it should.

This issue can be resolved, but doing so needlessly complicates the system. I really think storing due times is a better idea. Here's how the sequence above would look:

Enqueue event A with delay 10. The 'due time' is set to 10 (assume 'current time' is zero; I'm using a simple number for time, as it can be expressed that way). Enqueue event B with delay 5; due time is set to 5. Queue is now B(5) A(10). Five ticks elapse, and event B fires. Current time is now 5, event C is enqueued with delay 4. Adding this delay to the current time gives us 9, so the queue is C(9) A(10). Timer is set to fire after 4 ticks (9 - now equals 9 - 5 equals 4), and after four ticks, event C fires. Current time is now 9, queue is A(10), and the timer is set to fire after 1 tick. To me, this is a lot easier to follow, and the events all fire in the proper order and after the correct delay, within the limits of timer granularity (timer granularity applies to any implementation, not just mine).
__________________
A man's knowledge is like an expanding sphere, the surface corresponding to the boundary between the known and the unknown. As the sphere grows, so does its surface; the more a man learns, the more he realizes how much he does not know. Hence, the most ignorant man thinks he knows it all. - L. Sprague de Camp
lectricpharaoh is offline   Reply With Quote