Operating System - HP-UX
1822912 Members
3739 Online
109645 Solutions
New Discussion юеВ

Anyway to prevent busy waiting?

 
SOLVED
Go to solution
Henry Chua
Super Advisor

Anyway to prevent busy waiting?

I got a program which is written to wait for a condition to be meet before it will proceed with its job
say:
while (TRUE){
if ( Condition = TRUE){
do procedure();
}
}
so it will loop endlessly waiting for the condition to be met. Is there any other way to do this preventing unnecessary tying up of the CPU? Semaphore maybe?
6 REPLIES 6
TwoProc
Honored Contributor

Re: Anyway to prevent busy waiting?

Well, you could put in a sleep command in your loop - "sleep 60" inside of your loop will make the loop wait 1 minute before continuing with the next check...
We are the people our parents warned us about --Jimmy Buffett
Henry Chua
Super Advisor

Re: Anyway to prevent busy waiting?

Hi John, thanks for the input. Just for my info, is there anyway I can run the process on the background and let it behave like an interrupt so that it will not tied un unnecessary CPU time but yet constantly waiting for the right condition?
A. Clay Stephenson
Acclaimed Contributor

Re: Anyway to prevent busy waiting?

Semaphores are made to do this sort of thing. In your case, your would do a semop with IPC_NOWAIT set to false so that the process is suspended until another cooperating process adjusts the semval. Man semop for details. The other mechansism that you might want to use is wait(). The idea is that you would spawn a child process to do some processing and then exit and that would reawaken the calling process. Man 2 wait for details.
If it ain't broke, I can fix that.
Henry Chua
Super Advisor

Re: Anyway to prevent busy waiting?

Hi Stephenson,

Thanks for the info. Just a thought, if the cue for the execution of the procedure lies in whether a file is modified or not. Is it possible to utilise sempahore in this application? this seems to be a gray as the file may not be tied up by any process most of the time..

regards
Henry
A. Clay Stephenson
Acclaimed Contributor
Solution

Re: Anyway to prevent busy waiting?

While a file can serve the purpose of a semaphore, it would have the same problem as your original code. The only way to know if a file has been modified is to test in a loop. Unlike with semaphores, there is no mechanism to "wake" a process when a file has been modified.
If it ain't broke, I can fix that.
Henry Chua
Super Advisor

Re: Anyway to prevent busy waiting?

Thank guys for all your input, guess i still have to resort to using a loop at the end of the day..