Infinite Loop – Managing CPU Usage in Infinite While Loops

clinuxloopsperformance

I'm coding an script in C, which is going to check constantly an array of events, the idea is to check if the Date and time of certain event is equal to de current time and trigger something, i'm doing this with a while(1){}, but this approach causes a high CPU usage, do you have any suggestion of how can i do this with a lower CPU usage ?

Best Answer

The best way is to track what the next time is when you add to the array, then you sleep until that time.

So, when adding a new event to the array, you must decide if it is going to be triggered first, or later than the currently stored 'next event'. Then your loop simply sleeps (maybe periodically waking up every second or so to print an "I'm still running" diagnostic).

This will require a thread that wakes up to trigger the event must be synchronised with a mutex, so it can be prematurely woken up if a new event is added that is going to be fired sooner than the current next event. This thread then re-calculates the next time will be, sets the mutex and waits for either it to be triggered again or a timeout occurs where the timeout will be the right amount of time to wait for the next event's time.