开发者

why while loop is used for non-dying processes?

For applications that shouldn't die, should implement while loop, afaik. like

while(){
  key = getKeyPress();
  if(key)
    processKey开发者_运维技巧(key);

}

I can see 200 programs hanging on when I use "top". That means there are 200 while loops!

I expect every program to put hook for the events to the operating sys. When these events occur operating sys to call these hooks of program.

Web programmes executes javascript codes at the initialization. Then we hook for a button if clickes ($('button').click(myClickJs)), we hook for timer (setInterval) etc. We dont use a loop to wait whole events on a page. Such a approach saves much cpu time and resource.

Why there isn't such approach?


For "applications that shouldn't die", a loop MUST be implemented somewhere. You can not get around this.

In your example code, it is waiting for a key to be pressed before doing what needs to be done in response to that key press. After the key press is detected and processed, how do you reset it to wait for another key press (or other type of input)? The answer of course is to use a loop (as you have done).

This "outer" loop does not in any way reflect upon what is going on inside the routine 'getKeyPress()'. There are two modes in which this routine might possibly operate--polling and blocking.

If this is a polling routine, your example code will effectively busy-wait until a key is pressed. This is known to be an inefficient use of the processor (though for some problems it is the right solution).

If this is a blocking routine, the thread/task will block until such time as a key is pressed. While blocked, this thread/task will not be consuming any processor cycles, which will allow them to be used by another thread/task/process. For the purposes of this response, the specific details on how this blocking call is implemented are irrelevant. The important concept is that the thread/task may block.

Without the "outer" loop, you will only get one pass at detecting and processing any key presses, whether you have hooks or not.

Hope this helps.

0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜