Better game loops than endless loop + block?

2020-06-04 04:00发布

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?

9条回答
唯我独甜
2楼-- · 2020-06-04 04:27

MsgWaitForMultipleEvents combines GetMessage/PeekMessage functionality with a timeout and the ability to wait for kernel objects, such as a WaitableTimer.

I've used CreateWaitableTimer to set up my desired frame rate together with MsgWaitForMultipleEvents for message dispatching with great success for very smooth animation in the past, without busy-waiting. I wish other OSes had anything so nice.

查看更多
一纸荒年 Trace。
3楼-- · 2020-06-04 04:28

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!

查看更多
神经病院院长
4楼-- · 2020-06-04 04:29

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.

查看更多
登录 后发表回答