#include
int main() {
while(!DONE) {
/* check for stuff */
}
return 0;
}
The above code sample uses 100% cpu until DONE
You have several choices:
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.
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.
Use yield().
On windows, you can use Sleep(int milliseconds), defined on windows.h.
Sleep(0); is enough
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);