On Linux, the survey is conducted in good faith

When you have a hard polling about the status of something, I'm not really sure how to do a poll without interfering with other processes that want to use the CPU. For example, doing this:

while (state == BUSY) state = check_state();

      

seems like a waste of resources. I would think the best way to do this is:

while (state == BUSY) {
    sched_yield();
    state = check_state();
}

      

I would expect apex to list the process as sleep, even though it is consuming 100% of the CPU when it does so. So the process will be (hopefully) polling "nicely". But that's not what is happening. At the moment I have

while (state == BUSY) {
    sleep(1);
    state = check_state();
}

      

which is perfectly acceptable, but I feel it can be done better than this. Is there a standard practice for this?

+2


source to share


5 answers


Don't get hung up on sched_yield (), it tracks the detection of scheduler priorities very poorly, and even when it interacts well in terms of performance, it will do things like battery waste and power consumption metrics. If your application can tolerate latency, polling with a timeout (even short ones such as 10 Hz) is highly preferred if still not perfect.



The correct answer depends on what check_state () needs to be done. Are you absolutely sure you can't arrange things so that changes in your state are kernel-mapped events that you can block?

+3


source


I don't think you can use poll or epoll on?



+1


source


Unfortunately, there is no such thing as a fair survey. Polling is always a trade-off between response time and resource consumption: the shorter the polling period, the better the response time, but the higher the resource consumption. The longer the polling period, the more power you save, but the less reactive your application becomes.

Poll is always ugly, no matter how you look at it. If you are trying to do something right, you will need to use a more efficient mechanism, i.e. Notification. This means that your check_state () API is bad because it only allows you to poll for state; you need a function to notify you when the state changes. Typically, such a function makes some fd readable on state changes, so you can synchronously or asynchronously wait for events on fd and only wake up when such an event occurs.

+1


source


I think you could use libevent or libev .

Both provide the means to handle such things.

0


source


In my real-time work, I usually choose a reasonable timeout (like 10us) and twist the condition and RDTSC (timestamp counter).

If you want to hang for very long periods of time (like longer than 10ms), I would suggest putting in a small sleep statement so that other things have a chance to run.

0


source







All Articles