问题
Currently clock_nanosleep with CLOCK_MONOTONIC_RAW on Debian Jessie returns EOPNOTSUPP.
How to work around the issue and compensate for possible NTP adjustments which might get applied to CLOCK_MONOTONIC in the timer loop?
Is clock_nanosleep itself also affected by NTP adjustments? If adjustments happen while sleeping, will clock_nanosleep sleep longer that expected?
And should I be worried at all about possible CLOCK_MONOTONIC NTP adjustments in my specific case? What would be the largest possible "time jump" applied by NTP to CLOCK_MONOTONIC, considering that my code will be running on a system without real-time clock and it might lose Internet connection from time to time?
The long story. I'm using a simple loop to emulate audio file playback and I need to maintain consistent playback position.
clock_nanosleep with TIMER_ABSTIME flag seems to be doing the job fine, but I'm not sure if CLOCK_MONOTONIC is enough to avoid noticeable jumps in playback position.
Here is the code I'm using:
clock_gettime(CLOCK_MONOTONIC, &deadline);
// run until asked to stop
while(!need_quit(stop_mutex_signal)) {
// do stuff ...
// add time ms to previous deadline
deadline.tv_nsec += device->periodTime * NANOSECONDS_PER_MILLISEC;
// normalize the time to account for the second boundary
if(deadline.tv_nsec >= NANOSECONDS_PER_SEC) {
deadline.tv_nsec -= NANOSECONDS_PER_SEC;
deadline.tv_sec++;
}
if(clock_nanosleep(CLOCK_MONOTONIC, TIMER_ABSTIME, &deadline, NULL) != 0)
{
// something happened - error or exit signal, cannot continue
return;
}
}
I'm curious, why support for CLOCK_MONOTONIC_RAW in clock_nanosleep is not yet implemented? Does it mean that CLOCK_MONOTONIC is enough for most cases, even for audio/video synchronization?
回答1:
CLOCK_MONOTONIC is monotonic. It is not subject to any jumps, from ntp or otherwise. The only thing it is subject to is drift rate adjustment which is usually done by ntpd via adjtime or similar. For short intervals this adjustment is not going to be visible at all. In any case, as long as your system is not maliciously configured, it's much more accurate than CLOCK_MONOTONIC_RAW. As an example (made up numbers but they're probably in the realm of reasonableness) CLOCK_MONOTONIC_RAW might be running at a rate of 999950000 nanoseconds per actual second and CLOCK_MONOTONIC at a rate of 1000001000 nanoseconds per actual second.
来源:https://stackoverflow.com/questions/39064160/clock-nanosleep-does-not-yet-support-clock-monotonic-raw-how-to-deal-with-thi