proc.c
//PAGEBREAK: 42
// 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.
42
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.
42 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;
  int ticket;
  srand(ticks);
  for(;;){  
	      sti();
	      acquire(&ptable.lock);
	      int ticketsSum = countTickets();
	      ticket = rand(ticketsSum);
	      for(p = ptable.proc; p < &ptable.proc[NPROC]; p++){
		  if(p->state != RUNNABLE)
		      continue;
		  if((ticket - p->ntickets) >= 0) {
			ticket = ticket - p->ntickets;
			continue;
		  }
		  break;
	      }
	      if(p->state == RUNNABLE) {
		  proc = p;
		  switchuvm(p);
		  p->state = RUNNING;
		  swtch(&cpu->scheduler, proc->context);
		  switchkvm();
		  proc = 0;
	      }
	      release(&ptable.lock);
  }
}
void scheduler ( void ) { struct proc * p ; int ticket ; srand ( ticks ) ; for ( ; ; ) { sti ( ) ; acquire ( & ptable . lock ) ; int ticketsSum = countTickets ( ) ; ticket = rand ( ticketsSum ) ; for ( p = ptable . proc ; p < & ptable . proc [ NPROC ] ; p ++ ) { if ( p -> state != RUNNABLE ) continue ; if ( ( ticket - p -> ntickets ) >= 0 ) { ticket = ticket - p -> ntickets ; continue ; } break ; } if ( p -> state == RUNNABLE ) { proc = p ; switchuvm ( p ) ; p -> state = RUNNING ; swtch ( & cpu -> scheduler , proc -> context ) ; switchkvm ( ) ; proc = 0 ; } release ( & ptable . lock ) ; } }
PAGEBREAK: 42
Per-CPU process scheduler.
PAGEBREAK : 42 Per - CPU process scheduler .
// Enable interrupts on this processor. // Loop over process table looking for process to run. // Switch to chosen process.  It is the process's job // to release ptable.lock and then reacquire it // before jumping back to us. //cprintf("Context switching. pid=%d, pname=%s, p->ntickets=%d, ticket=%d, ticketsSum=%d\n", p->pid, p->name, p->ntickets, ticket, ticketsSum); // Process is done running for now. // It should have changed its p->state before coming back.