This is expanding on my comment above, but for the sake of completeness I am pasting what I've written in the commend here (and adding to it).
The general solution to this sort of problem is to wait for arrival of data and process it as it arrives (possibly caching newly arrived data as you're processing previously arrived data). As to the mechanics of the implementation - well, that depends on a concrete example. For example, often in a graphics processing application (games, for instance), the "game loop" is essentially what you describe (without sleeps). This is also encountered in GUI app design. For a design where the app waits for an event before processing, look to typical network client-server design.
As for the slowdown of the CPU, try the following code to observe significant slowdown:
while(true);
versus
while(true) sleep(1);
The reason the first slows down is because on each cycle the CPU checks if the condition in the loop evaluates to true
(that is, in this case, if true == true
). On the other hand, in the second example, the CPU checks if true == true
and then sleeps for 1ms
, which is significantly longer than the amount of time it takes to check true == true
, freeing the CPU to do other things.
Now, as for your example, presumably processing the data inside the loop takes significantly more CPU cycles than checking true == true
. So adding a sleep
statement will not help, but only worsen the situation.
You should leave it to the kernel to decide when to interrupt your process to dedicate CPU cycles to other things.
Of course, take what I wrote above with a grain of salt (especially the last paragraph), as it paints a very simplistic picture not taking into account your specific situation, which may benefit from one design versus another (I don't know, because you haven't provided any details).