April 27, 2024, 01:14:30 PM

News:

Own IWBasic 2.x ? -----> Get your free upgrade to 3.x now.........


Deadloop prevention

Started by sapero, April 30, 2009, 09:41:11 AM

Previous topic - Next topic

0 Members and 1 Guest are viewing this topic.

sapero

April 30, 2009, 09:41:11 AM Last Edit: April 30, 2009, 09:52:16 AM by sapero
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.