IonicWind Software

Announcements => User Offerings => Topic started by: sapero on April 30, 2009, 09:41:11 AM

Title: Deadloop prevention
Post by: sapero on April 30, 2009, 09:41:11 AM
Sometimes your program enters infinite loop and you are forced to terminate it, loosing all collected data. With this small library you can set a timeout for any function.
DEADLOOPCONTEXT DeadLoopContext;
DeadLoopContext.dwTimeout = 2000; // allow up to 2 seconds

if (InitDeadLoopProtection(&DeadLoopContext))
{
print("entering infinite loop");
while (1)
{
Sleep(1);
}
}
if (DeadLoopOccured(&DeadLoopContext))
{
MessageBox(0, "Deadloop detected.\n\nExiting from infinite loop", "");
}


InitDeadLoopProtection function creates a timer using timeSetEvent api. When the timer gets signalled, a custom callback function will be called. The timer and its callback runs in separate thread, so in the callback we can call SetThreadContext to break any infinite loop.

This will not work if the thread hungs in kernel mode, for example you are waiting for an event, or called Sleep, but after the thread execution returns to user mode, the loop will be terminated. For example, if you replace Sleep(1) with Sleep(10000), the WHILE loop will be terminated after 10 seconds.

It uses OpenThread api, so at least Windows ME is required.
Included examples for Aurora and Emergence.