C Main Loop without 100% cpu

pwseo picture pwseo · Aug 3, 2009 · Viewed 19.6k times · Source
#include <stdio.h>

int main() {
  while(!DONE) {
    /* check for stuff */
  }
  return 0;
}

The above code sample uses 100% cpu until DONE is true. How can I implement a program that loops and only terminates when DONE, but which doesn't use 100% cpu? Modern languages use something like App.ProcessMessages or something like that to give the OS the control for the moment and then return to the loop.

I'm new at C, obviously... using latest GCC, linux and windows (a portable solution would be great!)

Answer

Adriaan picture Adriaan · Aug 3, 2009

It depends what you want to do inside this loop.

If you are waiting inside the loop (i.e. if keypressed { do something} then your mechanism will waste system resources giving nothing in return. A faster processor will just make more idle loops. This can be solved by waiting for events Not just sleep, but preferably an event which triggers that something meaningful can be done. For instance, a file operation (stdin is also a file) would be a portable mechanism. This will give way to other applications until data is available. When you become more specific it may be required to dive into semaphores or signals which are often OS dependent. An abstraction layer can resolve this.

If you are doing something useful (i.e. processing a lot of data), then 100% cpu load just means that the processor is used in the most efficient way. You can rely on the operating system to give way to other and possibly higher priority tasks.

Using a function like sleep will lower cpu usage, but your application will be slower. It will require to get a tradeoff between acceptable performance and cpu load. The maximum execution speed will be defined by your sleep parameter, and no longer by the cpu speed. Also, if power is a concern (i.e. battery life time), then this will require the cpu to wakeup (end of sleep period) with no work to be done; i.e. a different waste of system resources.