开发者

Why is clock_nanosleep preferred over nanosleep to create sleep times in C?

开发者 https://www.devze.com 2023-04-13 08:34 出处:网络
Which one of the two functions is better #include <time.h> int clock_nanosleep(clockid_t clock_id, int flags, const struct timespec *rqtp, struct timesp开发者_如何学编程ec *rmtp);

Which one of the two functions is better

#include <time.h>
int clock_nanosleep(clockid_t clock_id, int flags, const struct timespec *rqtp, struct timesp开发者_如何学编程ec *rmtp);

OR

#include <time.h>
int nanosleep(const struct timespec *rqtp, struct timespec *rmtp);


The advantages of clock_nanosleep over nanosleep are:

  1. You can specify an absolute time to sleep until rather than an interval to sleep. This makes a difference for the realtime (wall time) clock, which can be reset by the administrator or ntpd, etc. With nanosleep and precalculating the interval to sleep to reach a given absolute time, you'll fail to wake if the clock is reset and the desired time arrives "early". Also, there's a race condition with scheduling using interval times: If you compute the interval you want to sleep, but you get preempted before calling nanosleep and don't get scheduled again for a while, you'll again sleep too long.
  2. You can sleep on timers other than the realtime clock. The most useful is usually the monotonic clock (which can't be reset and increases monotonically with the progression of actual time), but there are also other interesting applications like having one thread in a multi-threaded process sleep on the process's cpu time clock (so it wakes after the process has used a given amount of cpu time).


On my system, man 2 clock_nanosleep explains the differences between the two functions thus:

   Like  nanosleep(2), clock_nanosleep() allows the caller to sleep for an
   interval specified with nanosecond precision.  It differs  in  allowing
   the  caller  to select the clock against which the sleep interval is to
   be measured, and in allowing the sleep  interval  to  be  specified  as
   either an absolute or a relative value.

   The clock_id argument [...] can have one of the following values:

   CLOCK_REALTIME   A settable system-wide real-time clock.

   CLOCK_MONOTONIC  A non-settable, monotonically  increasing  clock  that
                    measures time since some unspecified point in the past
                    that does not change after system startup.

   CLOCK_PROCESS_CPUTIME_ID
                    A settable per-process clock that  measures  CPU  time
                    consumed by all threads in the process.

0

精彩评论

暂无评论...
验证码 换一张
取 消

关注公众号