Hi,
I'm studying programming and there's something I'm wondering about. Many tutorials and books demonstrate a loop like this:
For example in a game it is for checking if a quit flag is set, by the user entering "q" or some such.
Then, recently I wrote a little C++ program using the SDL library, which has that main "game loop" which polls over and over to see if an exit command was sent (e.g. by closing the window, or pressing alt+F4). I realized that it is using 100% CPU. Even just executing an empty infinite loop in C/C++ does the same.
Now, my questions:
Edit:
I've looked at the Angband code quickly. From main() it calls play_game(), which looks like this: (the ellipses are snipped lines. I only copied the ones which have "break")
So it does have an infinite loop. But it doesn't eat 100% CPU, most I've seen from top is 1%. Now I'm wondering, how is Angband's infinite loop different from my infinite loops which eat 100% CPU? It isn't immediately obvious to me what the difference is. I'll read more from Angband code, it looks really neat and clean.
If someone knows then please tell me.
I'm studying programming and there's something I'm wondering about. Many tutorials and books demonstrate a loop like this:
Code:
while (!condition)
{ ... }
For example in a game it is for checking if a quit flag is set, by the user entering "q" or some such.
Then, recently I wrote a little C++ program using the SDL library, which has that main "game loop" which polls over and over to see if an exit command was sent (e.g. by closing the window, or pressing alt+F4). I realized that it is using 100% CPU. Even just executing an empty infinite loop in C/C++ does the same.
Now, my questions:
- Is that a bad thing to do?
- Does production code have loops like that? Do actual finished video games have a main loop like that? If so, does it affect performance to become worse? I remember reading text from different places that says "the logic of all games depends on a kind of loop like that, which checks forever for quit conditions", and now it seems strange why would we do that if it eats 100% CPU.
- How to solve it?
Edit:
I've looked at the Angband code quickly. From main() it calls play_game(), which looks like this: (the ellipses are snipped lines. I only copied the ones which have "break")
Code:
while (TRUE)
{
...
/* Handle "quit and save" */
if (!p_ptr->playing && !p_ptr->is_dead) break;
...
/* Handle "death" */
if (p_ptr->is_dead) break;
...
}
So it does have an infinite loop. But it doesn't eat 100% CPU, most I've seen from top is 1%. Now I'm wondering, how is Angband's infinite loop different from my infinite loops which eat 100% CPU? It isn't immediately obvious to me what the difference is. I'll read more from Angband code, it looks really neat and clean.
If someone knows then please tell me.