MRC/Tutorials/The EMC environment
The main loop
When we want to control and monitor a piece of hardware, we often want to perform a series of steps, computations, procedures, etc., in a repetitive manner. When we talk about doing something repeatedly in software, the first 'control flow statement' that comes to mind is a loop. So, lets' create a loop!
#include <iostream>
int main()
{
while (true)
{
std::cout << "Hello World!" << std::endl;
}
return 0;
}
Remember that while the condition in the while statement is true, the body of the while loop will be executed. In this case, that is forever! Fortunately you can always interrupt the program using ctrl-C from the command line. By the way, the default behavior is that this directly kills your program, so all statements after the while loop (if there were any) would never be executed. You can verify this by putting a print statement there. You will see it is never called...
So, it's a nice loop, but there's at least three things wrong with it:
- 1. It runs forever, never 'gracefully' shutting down (only by user interruption)
- 2. It runs as fast as possible!
- 3. It doesn't do much useful except for flooding the screen...
For now, let's focus on point 2). Your operating system schedules the execution of programs: if multiple programs are running simultaneously, it gives each program a short period of time to perform their executions and then jumps to the next. What our program does in that time slice is printing 'Hello World!' as fast as it can! It is like a horrible, zappy kid taking up all of your time as soon as you give it some attention. We can be better than that.