1

The first branch in the loop's body has a continue statement, but I'm not exactly sure why. I'm under the impression that a continue statement here is unnecessary, and that having an if-statement like if(p->state == RUNNABLE) with the rest of the loop's body inside the if-statement's body would be better (i.e. it would make control-flow more explicit).

I'm thinking it could be to avoid nesting for readability's sake. Or am I missing out on something here?

 // Per−CPU process scheduler.
 // Each CPU calls scheduler() after setting itself up.
 // Scheduler never returns. It loops, doing:
 // − choose a process to run
 // − swtch to start running that process
 // − eventually that process transfers control
 // via swtch back to the scheduler.
 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++) {
       
       // What's the purpose of this?
       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);

   }
 }
sbw
  • 46
  • 4
  • 4
    The scheduler shouldn't schedule a process that can't run if it is scheduled. Using `continue` skips the rest of the loop to the `p++` in the 'increment' section of the inner `for` loop. – Jonathan Leffler Aug 01 '20 at 03:13
  • 2
    This is just a style choice. Many programmers prefer to use `continue` rather than nest almost the entire loop body in an `if`. – Barmar Aug 01 '20 at 04:05
  • `continue` makes the logic clearer, since it tells you that the `if` controls the entire loop body. – Barmar Aug 01 '20 at 04:05
  • As you've pretty much mentioned, there is no run-time difference between adding an `if` scope and kicking the flow back to the beginning of the loop with `continue`. TBH, i personally prefer the `continue`. While this isn't applicable to the specific piece of code, nesting scope in a scope in a scope... can make it really hard to read. – Boris Lipschitz Aug 01 '20 at 04:17
  • Speaking about styles... how comes nobody notices the `for (;;)` :-D – Boris Lipschitz Aug 01 '20 at 04:18

0 Answers0