The concept behind this is that, you never let the process iterations stack up, clogging the call stack (which consumes all resources), and provide or yield adequate resources for other processes, both internal and external, to make sure that all necessary operations are working as expected.
Take for example the following code:
while(TRUE) {
//do something
}
Try running the above infinite loop. As it is, without anything to break from or what. This will take your CPU utilization to 100% and load average to very critical levels until it crashes your system. This is how an "unyielding loop" looks like. Most of the similar cases looks a lot like it which uses loops like for, foreach, and do.
The solution to the above code is simple. Simply add a "pause" or a "yield". In this case, I'm gonna use a popular function "sleep" for some *nix OS programming languages. See below.
while(TRUE) {
//do something
sleep(1)
}
Some people might argue that a "1-second" pause is too long for an inexpensive, long running or infinite loop. Maybe it's just a counter or something like that. In that case, you might want to use microsecond pauses instead. Just make sure that you pause just enough time to take first iteration to finish processing and release memory and you should be yielding CPU resources just fine. In PHP, there's a function called "usleep" that does exactly that. There should be equivalents in other programming languages. See below.
while(TRUE) {
//do something
usleep(50) // equivalent to 0.050 seconds
}
No comments:
Post a Comment