当前位置: 代码迷 >> 综合 >> schedule()函数篇
  详细解决方案

schedule()函数篇

热度:58   发布时间:2024-01-10 05:45:48.0

     内核中schedule()函数用来实现进程的调度(kenel/sched.c中)。函数代码以及注释如下:

/** schedule() is the main scheduler function.*/
asmlinkage void __sched schedule(void)
{struct task_struct *prev, *next;unsigned long *switch_count;struct rq *rq;int cpu;need_resched:preempt_disable();    //禁止内核抢占cpu = smp_processor_id(); //获取当前CPUrq = cpu_rq(cpu);    //获取该CPU维护的运行队列(run queue)rcu_note_context_switch(cpu);  //更新全局状态,标识当前CPU发生上下文的切换。prev = rq->curr;    //运行队列中的curr指针赋予prev。schedule_debug(prev); if (sched_feat(HRTICK))hrtick_clear(rq);raw_spin_lock_irq(&rq->lock); //锁住该队列switch_count = &prev->nivcsw;  //记录当前进程的切换次数if (prev->state && !(preempt_count() & PREEMPT_ACTIVE)) {     //是否同时满足以下条件:1该进程处于停止状态,2该进程没有在内核态被抢占。if (unlikely(signal_pending_state(prev->state, prev))) {  //若不是非挂起信号,则将该进程状态设置成TASK_RUNNINGprev->state = TASK_RUNNING;} else {   //若为非挂起信号则将其从队列中移出/** If a worker is going to sleep, notify and* ask workqueue whether it wants to wake up a* task to maintain concurrency.  If so, wake* up the task.*/if (prev->flags & PF_WQ_WORKER) {     struct task_struct *to_wakeup;to_wakeup = wq_worker_sleeping(prev, cpu);if (to_wakeup)try_to_wake_up_local(to_wakeup);}deactivate_task(rq, prev, DEQUEUE_SLEEP);  //从运行队列中移出/** If we are going to sleep and we have plugged IO queued, make* sure to submit it to avoid deadlocks.*/if (blk_needs_flush_plug(prev)) {raw_spin_unlock(&rq->lock);blk_schedule_flush_plug(prev);raw_spin_lock(&rq->lock);}}switch_count = &prev->nvcsw;  //切换次数记录}pre_schedule(rq, prev); if (unlikely(!rq->nr_running))idle_balance(cpu, rq);put_prev_task(rq, prev);  next = pick_next_task(rq);  //挑选一个优先级最高的任务将其排进队列。clear_tsk_need_resched(prev); //清除pre的TIF_NEED_RESCHED标志。rq->skip_clock_update = 0;if (likely(prev != next)) { //如果prev和next非同一个进程rq->nr_switches++;  //队列切换次数更新rq->curr = next;++*switch_count;  //进程切换次数更新context_switch(rq, prev, next); /* unlocks the rq */   //进程之间上下文切换/** The context switch have flipped the stack from under us* and restored the local variables which were saved when* this task called schedule() in the past. prev == current* is still correct, but it can be moved to another cpu/rq.*/cpu = smp_processor_id();rq = cpu_rq(cpu);} else   //如果prev和next为同一进程,则不进行进程切换。raw_spin_unlock_irq(&rq->lock);  post_schedule(rq);preempt_enable_no_resched();if (need_resched())  //如果该进程被其他进程设置了TIF_NEED_RESCHED标志,则函数重新执行进行调度goto need_resched;
}

注:以上内核代码版本为2.6.39。


  相关解决方案