理解Linux内核调度程序

4

我正在学习Linux内核,并试图弄清楚循环调度算法的工作原理。在kernel\sched_rt.c文件中,有一个名为task_tick_rt的方法,定义如下:

static void task_tick_rt(struct rq *rq, struct task_struct *p, int queued)
{
    update_curr_rt(rq);

    watchdog(rq, p);

    /*
     * RR tasks need a special form of timeslice management.
     * FIFO tasks have no timeslices.
     */
    if (p->policy != SCHED_RR)
            return;

    if (--p->rt.time_slice)
            return;

    p->rt.time_slice = DEF_TIMESLICE;

    /*
     * Requeue to the end of queue if we are not the only element
     * on the queue:
     */
    if (p->rt.run_list.prev != p->rt.run_list.next) {
            requeue_task_rt(rq, p, 0);
            set_tsk_need_resched(p);
    }

除了有一个无用的queued参数之外,我不明白这段代码试图通过if(--p->rt.time_slice)检查达到什么目的。我不理解为什么任务列表指针p被减1,换句话说,为什么该方法要检查前一个任务而不是当前任务?如有任何疑问,请解释清楚。

1个回答

7
请查看c运算符优先级:http://en.wikipedia.org/wiki/Operators_in_C_and_C%2B%2B#Operator_precedence ->运算符比前缀++的优先级更高,因此可以将这个特定条件写成:
if (--(p->rt.time_slice))

换句话说,被减少的是时间片,而不是指针。
queued 参数在这里似乎没有用处,但它有存在的理由。特别要注意 task_tick_rt() 被调用的位置。它唯一的引用是在将其分配给 struct sched_class.task_tick 函数指针时: http://lxr.free-electrons.com/source/kernel/sched/rt.c#L1991 因此,我们可以看到每个调度算法都有自己的 struct sched_class 函数向量,内核将调用它们提供的调度服务。如果我们查看其他算法,我们会发现完全公平调度(CFS)算法也有自己的 struct sched_class 实例,名为 fair_sched_classhttp://lxr.free-electrons.com/source/kernel/sched/fair.c#L6179 在 CFS 情况下,.task_tick 成员指向 task_tick_fair()http://lxr.free-electrons.com/source/kernel/sched/fair.c#L5785 请注意,task_tick_fair() 实际上使用了 queued 参数。因此,在调用 .task_tick 成员时(这里这里),会向 queued 参数传递 0 或 1。因此,虽然 task_tick_rt() 没有使用它,但 queued 参数仍必须存在,以便 struct sched_class 函数向量中的函数指针类型都能匹配。
简而言之,struct sched_class 函数向量指定了调度算法与内核其余部分之间的接口。queued 参数在某些算法选择使用时存在,但在轮换调度的情况下,它被简单地忽略掉了。

完美的解释。谢谢您,先生! - user2872534
@DigitalTrauma 感谢您对sched_class目的的解释。我知道有两种调度策略SCHED_FIFOSCHED_RR。然而,查看http://lxr.missinglinkelectronics.com/#linux+v3.10/kernel/sched/rt.c#L1 sched/rt.c,我无法弄清楚sched_class如何协助选择使用哪种策略。 - newprint
@newprint - 请将此作为一个新问题提出。 - Digital Trauma

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接