Every game tutorial and game framework (even the rather new XNA framework) start off with a never ending loop that has an equivalent of DoEvents() to prevent the OS from locking up.
Comming from a non-game based perspective I feel this kind of code smells rather funky.
Are there no better alternatives?
--EDIT--
A lot of answers say every program is basically a loop. True, but I feel the loop should be performed by your OS, not by you. Only the OS has all the information it needs to distribute its resources in an optimal way. Or am I missing an important point here?
MsgWaitForMultipleEvents
combinesGetMessage
/PeekMessage
functionality with a timeout and the ability to wait for kernel objects, such as aWaitableTimer
.I've used
CreateWaitableTimer
to set up my desired frame rate together withMsgWaitForMultipleEvents
for message dispatching with great success for very smooth animation in the past, without busy-waiting. I wish other OSes had anything so nice.if you not feel comfortable about it, package it with class and interface,
that is what we say "open and close principle": open the interface never changed, close the dirty part.
why we use loop? because it is the basic structure of our computer!
The better loop is an endless loop with blocking call to dispatch events/messages. If there's nothing to be done, you should indeed not sleep, but block while waiting for the OS. But if the OS indeed doesn't block when you poll for events, sleeping between polling is the only solution to prevent 100% CPU use.