Monday, June 30, 2008

taming the infinite loop

Because I have made this mistake more times than I can count, I thought I'd write a bit about it.

In operating systems we often learn this type of construct in order for sharing resources:

ask for a resource
if (resource isn't free){
while (resource isn't free){
do nothing
}
}


use the resource
release the resource

This is kind of a semaphore, allowing only one process to access the resource at a time. It works great for operating systems. However it is not an okay construct to use in a single process.

Why the difference? Well, in operating systems, each process is scheduled out--one process does not have to complete before another process executes. So, in the middle of that busy wait, the operating system stops that process from executing and gives the other process(es) a chance to execute. If it didn't, then that first process with the busy wait would never complete because all the CPU time would be used just waiting for that while loop to be over instead of executing the other process that's currently using the resource. That's called deadlock.

Deadlock is exactly what happens when you use that kind of construct in a single, non-threaded program. Instead of executing that other function all your resources are dedicated to wait in that busy loop.

Sometimes this kind of thing is necessary, though. In the program I'm working on right now, I need a function to wait until an object is not null in order to continue. So I've been working for three days on this and this morning I finally realized that I was in deadlock like that. Easy solution: add a timer.

function myFunction(){
if (we're calling this function for the first time)
send request for the resource
else
after a set amount of time call timerFunction
}

function timerFunction(){
if (the resource is available)
do what I need to with it
else
call myFunction
}

Problem solved. While that timer is waiting to execute, it gives the other functions a chance to return that resource.

And now to more interesting problems, such as data logging over a web application. Eww. The stateless nature of web programming makes this an unhappy task. Yay PHP sessions!

No comments: