Sikau

Operating systems · Day 3 · about 40 min

Round robin and time slices

Preemption with a quantum: fair turns for everyone.

Everyone gets a turn

Interactive systems can't let one job hog the CPU. Round robin gives each ready process a time slice (quantum); when it's used up, a timer interrupt preempts the process and puts it at the back of the queue. Small quanta feel snappy but waste time on context switches.

The queue in motion

function roundRobin(jobs, quantum) {
  const pending = [...jobs].sort((a, b) => a.arrival - b.arrival);
  const left = Object.fromEntries(jobs.map((j) => [j.id, j.burst]));
  const queue = [];
  const slices = [];
  const finish = {};
  let time = 0;
  const admit = () => {
    while (pending.length && pending[0].arrival <= time) queue.push(pending.shift().id);
  };
  admit();
  while (queue.length || pending.length) {
    if (!queue.length) {
      time = pending[0].arrival; // idle until the next arrival
      admit();
      continue;
    }
    const id = queue.shift();
    const run = Math.min(quantum, left[id]);
    slices.push([id, time, time + run]);
    time += run;
    left[id] -= run;
    admit(); // newcomers join the queue before the preempted job
    if (left[id] > 0) queue.push(id);
    else finish[id] = time;
  }
  return { slices, finish };
}

The rest of this lesson

  • What a context switch costsexplain
  • Tracing round robinexplain
  • A timer interruptorder
  • Quantum sizematch
  • Simulate round robinwrite code
  • Badge quizquiz
  • What you learnedrecap

Continue this lesson free — run real code in your browser

Continue with Google

See all 12 lessons of Operating systems