当程序的计时器小于 4ms 时,抢占如何在 Linux 上工作?

ron*_*sak 7 linux scheduling sleep

大多数 Linux 系统中的 jiffies 默认为 250(4ms)。问题是当程序的 usleep() 小于 4ms 时会发生什么?当然,它在预定时按应有的方式工作。但是当linux调度器取出这个程序等待时会发生什么,因为另一个程序必须运行?在这种情况下,抢占是如何工作的?

我应该避免等待这么小的自定义程序吗?他们不可能是准确的,是吗?

Jim*_*ris 7

请参阅time(7)及其引用的联机帮助页。摘录:

High-Resolution Timers
   Before Linux 2.6.21, the accuracy of timer and sleep system calls  (see
   below) was also limited by the size of the jiffy.

   Since  Linux  2.6.21,  Linux  supports  high-resolution  timers (HRTs),
   optionally configurable via CONFIG_HIGH_RES_TIMERS.  On a  system  that
   supports  HRTs,  the  accuracy  of  sleep  and timer system calls is no
   longer constrained by the jiffy, but instead can be as accurate as  the
   hardware  allows  (microsecond accuracy is typical of modern hardware).
   You can determine  whether  high-resolution  timers  are  supported  by
   checking  the resolution returned by a call to clock_getres(2) or look?
   ing at the "resolution" entries in /proc/timer_list.

   HRTs are not supported on all hardware architectures.  (Support is pro?
   vided on x86, arm, and powerpc, among others.)
Run Code Online (Sandbox Code Playgroud)

一条评论表明你不能睡得少于一瞬间。那是不正确的;使用 HRT,您可以。试试这个程序:

/* test_hrt.c */
#include <time.h>
main()
{
        struct timespec ts;
        int i;

        ts.tv_sec = 0;
        ts.tv_nsec = 500000;  /* 0.5 milliseconds */
        for (i = 0; i < 1000; i++) {
                clock_nanosleep(CLOCK_MONOTONIC, 0, &ts, NULL);
        }
}
Run Code Online (Sandbox Code Playgroud)

编译它:

$ gcc -o test_hrt test_hrt.c -lrt
Run Code Online (Sandbox Code Playgroud)

运行:

$ time ./test_hrt

real    0m0.598s
user    0m0.008s
sys     0m0.016s
Run Code Online (Sandbox Code Playgroud)

正如您所看到的,0.5 毫秒延迟的 1000 次迭代只花费了 0.5 秒多一点,正如预期的那样。如果clock_nanosleep真的等到下一刻再回来,那至少需要4秒钟。


现在最初的问题是,如果您的节目被安排在那个时间,会发生什么?答案是这取决于优先级。即使在您的程序运行时调度了另一个程序,如果您的程序具有更高的优先级,或者调度程序决定是您的程序运行的时间,它也会在clock_nanosleep超时返回后再次开始执行。它不需要等到下一个瞬间发生。您可以尝试在运行其他占用 CPU 的软件的同时运行上面的测试程序,您会看到它仍然在相同的时间内执行,特别是如果您使用例如增加优先级

$ time sudo schedtool -R -p 99 -e ./test_hrt
Run Code Online (Sandbox Code Playgroud)