C Main Loop without 100% cpu

前端 未结 11 2366
半阙折子戏
半阙折子戏 2020-12-14 08:53
#include 

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

The above code sample uses 100% cpu until DONE

11条回答
  •  渐次进展
    2020-12-14 09:01

    You have several choices:

    1. Use sleep() to force the process to suspend periodically and allow other process to use the CPU
    2. Run at a lower priority level - which will cause the OS to assign less CPU time
    3. Use a mutex or other synchronization object to detect when work is available - which will keep the process from consuming any CPU time unless it is actually doing work
    4. If you get work faster than you can process it - you may still need to use some sort of sleep/priority model to avoid completely consuming the CPU.

    Option #2 can be tricky to do in a platform/OS neutral manner. Your best bet is to launch the process and change its priority in the runtime environment.

提交回复
热议问题