When you’ve got a tight loop polling the status of something, I’m not quite sure how to do the polling without getting in the way of other processes wanting to use the CPU. For instance, doing this:
while (state == BUSY) state = check_state();
seems like a waste of resources. I would think the best way to do this would be:
while (state == BUSY) {
sched_yield();
state = check_state();
}
I’d expect that top would list the process as sleeping, even if it does consume 100% of the CPU while it’s doing this. This way, the process would (I hope) poll “nicely”. But that’s not what happens. At the moment I have
while (state == BUSY) {
sleep(1);
state = check_state();
}
which is perfectly acceptable, but I feel like it could be done better than this. Is there a standard practice for doing this?
Don’t spin on sched_yield(), it mucks up the scheduler’s priority detection very badly and even when it interoperates well from a performance perspective will do things like wreck battery life and power consumption metrics. If your application can tolerate the latencies, polling with a timeout (even short ones like 10Hz) is very much preferable, if still not ideal.
The right answer depends on what check_state() actually needs to do. Are you absolutely sure you can’t arrange things so that your state changes are kernel-visible events that you can block on?