PDA

View Full Version : Potential race condition with timers



raal
December 8th, 2007, 02:49 PM
Allow me to give an example:

myTimer1 :Timer = new Timer(500);
myTimer2 :Timer = new Timer(1000);

myTimer1.addEventListener("timer", TimerFunctionOne);
myTimer2.addEventListener("timer2",TimerFunctionTwo);

MyTimer1.start();

//------------------------
function TimerFunctionOne()
{
//do some operation here
myTimer1.stop();
myTimer2.start();
}

function TimerFunctionTwo()
{
//do some operation here
myTimer2.stop();
myTimer1.start();
}
--------------------------

Now for the tricky bit. Suppose you want this in a class, and you want the ability to pause the class. I can add states to the class which describe what it is doing at the moment, and then stop the relevant timers. However, I can't seem to find a way to avoid the race condition where the pause function on the object is called just as one of the functions have been called through the timer, and then starts a timer again.

I can add an "if (!paused)" to the timer starters in TimerFunctionOne/Two, but that still leaves a theoretical hole (although small).

So, any thoughts on this?

raal

jinushaun
December 9th, 2007, 11:42 AM
Can you provide a more concrete example? As a general rule, I try not to rely on timers to change/watch the state of an object because you inevitably run into race conditions. I prefer writing and dispatching custom events.

raal
December 9th, 2007, 06:09 PM
I'm not sure how to give more information without posting a Huge Chunk(tm) of code.

I think it boils down to a design problem, but I cant find a way around it.

A better example than the last one:

Timer1 = new Timer(10);
Timer1.addEventListener("timer",doSomething);

addEventListener(KeyboardEvent.KeyDown,pauseTimer) ;

private function doSomething(e:TimerEvent)
{
// do a calculation that takes 9 ms here, to maximize chance of a race.
trace(/*result of calculation*/);
}

private function pauseTimer(e:KeyboardEvent)
{
Timer1.Stop();
}

I can never be sure that a trace does not happen AFTER the user has pressed the keyboard.

raal