XV6-循环调度程序

时间:2014-05-23 16:28:54

标签: c for-loop process scheduler xv6

我正在我的xv6中实现一个新的调度程序,要做到这一点,我需要了解它的工作方式,我面临一个有线问题,我无法真正理解for循环如何抛出进程

这是原始代码:

void
scheduler(void){
  struct proc *p;

  for(;;){
  // Enable interrupts on this processor.
  sti();

 // Loop over process table looking for process to run.
 acquire(&ptable.lock);
 for(p = ptable.proc; p < &ptable.proc[NPROC]; p++){
   if(p->state != RUNNABLE)
     continue;

  // Switch to chosen process.  It is the process's job
  // to release ptable.lock and then reacquire it
  // before jumping back to us.
  proc = p;
  switchuvm(p);
  p->state = RUNNING;
  swtch(&cpu->scheduler, proc->context);
  switchkvm();

  // Process is done running for now.
  // It should have changed its p->state before coming back.
  proc = 0;
}
release(&ptable.lock);

 }
}

所以我尝试了一个简单的事情,我做了for循环,第一个应该循环抛出所有proc并计算它们没有做任何其他事情,第二个应该循环并运行它们原来的一个,事情是没有像我预期的那样工作,发生的事情是它从第一个循环运行一个循环然后从第二个循环运行一个循环,依此类推

void
scheduler(void)
{
struct proc *p;
int FirstCounter=0;
int SecCounter=0;
for(;;){
  // Enable interrupts on this processor.
  sti();
  // Loop over process table looking for process to run.
  acquire(&ptable.lock);
  for(p = ptable.proc; p < &ptable.proc[NPROC]; p++){
    if(p->state != RUNNABLE)
      continue;
    counter++;
    cprintf("1st counter  = %d\n",FirstCounter); 
}
    for(p = ptable.proc; p < &ptable.proc[NPROC]; p++){
      if(p->state != RUNNABLE)
        continue;

      // Switch to chosen process.  It is the process's job
      // to release ptable.lock and then reacquire it
      // before jumping back to us.
        proc = p;
        switchuvm(p);
        p->state = RUNNING;
        swtch(&cpu->scheduler, proc->context);
        switchkvm();



        // Process is done running for now.
        // It should have changed its p->state before coming back.
        proc = 0;
        cprintf("2nd counter  = %d\n",SecCounter); 
    }


release(&ptable.lock);

} }


,输出就是那样,

.
.
.
1st counter  = 14
2nd counter  = 15
1st counter  = 15
2nd counter  = 16
.
.

为什么会这样?

1 个答案:

答案 0 :(得分:0)

我试过了,得到了同样的结果。

但是,当你打印进程的pid时,你会发现pid = 1 and pid = 2,我认为它们是init和页面守护进程。

我不知道init进程和页面守护进程的打印。但是,当您尝试fork()新进程时,您将按照您的想法获得打印。