0

我正在我的 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并计算它们而不做任何其他事情,第二个应该循环并像原来的那样运行它们,事情就是这样没有像我预期的那样工作,发生的事情是它从第一个 for 循环运行一个循环,然后从第二个循环运行一个循环,依此类推

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
.
.

为什么会这样?

4

1 回答 1

0

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

但是,当您打印进程的 pid 时,您会发现pid = 1 and pid = 2,我认为它们是 init 和 page daemon 进程。

我不知道初始化进程和页面守护进程的打印。但是,当您尝试fork()新工艺时,您会得到您所想的打印效果。

于 2015-03-19T21:58:57.383 回答