为什么clock_nanosleep优于nanosleep来在C中创建睡眠时间?

pay*_*s4u 10 c linux system-calls linux-kernel

这两个功能中哪一个更好

#include <time.h>
int clock_nanosleep(clockid_t clock_id, int flags, const struct timespec *rqtp, struct timespec *rmtp);
Run Code Online (Sandbox Code Playgroud)

要么

#include <time.h>
int nanosleep(const struct timespec *rqtp, struct timespec *rmtp);
Run Code Online (Sandbox Code Playgroud)

R..*_*R.. 16

clock_nanosleep超过的优点nanosleep是:

  1. 您可以指定一个绝对的时间睡觉,直到而非间隔睡觉.这对于实时(挂起时间)时钟有所不同,可以由管理员ntpd等重置.使用nanosleep并预先计算睡眠时间间隔以达到给定的绝对时间,如果时钟复位,您将无法唤醒期望的时间到了"早".此外,还存在使用间隔时间进行调度的竞争条件:如果您计算要休眠的间隔,但是在呼叫之前被抢占nanosleep并且暂时不再安排,则您将再次睡眠时间过长.
  2. 您可以在实时时钟以外的计时器上睡觉.最有用的通常是单调时钟(不能复位并随着实际时间的推移而单调增加),但也有其他有趣的应用程序,例如在多线程进程中有一个线程睡眠进程的cpu时钟(因此它在进程使用了​​给定量的cpu时间后唤醒).

  • 只是想添加注释以防止混淆... Linux 中的 nanosleep() 使用 CLOCK_MONOTONIC 时钟。所以如果你想在 Linux 中使用 CLOCK_MONOTONIC 以外的时钟,那就是你需要 clock_nanosleep() 的时候。 (3认同)

NPE*_*NPE 7

在我的系统上,man 2 clock_nanosleep解释了这两个函数之间的差异:

   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.