C Main Loop without 100% cpu

前端 未结 11 2320
半阙折子戏
半阙折子戏 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.

    0 讨论(0)
  • 2020-12-14 09:01

    What exactly are you checking for?

    If you're checking something volatile that is changed by hardware or another process, just call sleep in your loop.

    If you are waiting on a file descriptor or a network socket descriptor, you will want to use select or poll in your loop to wait for the descriptor to have data ready for consumption.

    0 讨论(0)
  • 2020-12-14 09:05

    Use yield().

    0 讨论(0)
  • 2020-12-14 09:05

    On windows, you can use Sleep(int milliseconds), defined on windows.h.

    0 讨论(0)
  • 2020-12-14 09:11

    Sleep(0); is enough

    0 讨论(0)
  • 2020-12-14 09:17

    If I understood right, you said in the comments that DONE can be changed from other threads. If so, condition variables make sense. With pthreads, one would do:

    In the thread that waits:

    pthread_mutex_lock(&mutex);
    while (!DONE) {
         pthread_cond_wait(&cond, &mutex);
    }
    pthread_mutex_unlock(&mutex);
    

    In other threads, when DONE is changed:

    pthread_mutex_lock(&mutex);
    DONE = 1;
    pthread_cond_signal(&cond);
    pthread_mutex_unlock(&mutex);
    
    0 讨论(0)
提交回复
热议问题