ENع
←Round robin
Lesson 14 · CPU scheduling

Round robin and the time slice

14 min11 steps5 questionsIntermediate
About this lesson

Running each job to the end is simple, but a job at the back of the line waits a long time before it even starts. Round robin fixes that: every job gets a short turn, a time slice, and the timer interrupt takes the CPU back when the turn is over. Follow three 5 ms jobs sharing one CPU in 1 ms slices, slice by slice, and see why they all start sooner but finish later. It builds on the lessons on the context switch and the timer interrupt, and on turnaround, response time and fairness; First come first served and shortest job first is the policy it is compared against.

You'll learn to

Tick what you feel confident about. These self-checks do not affect your lesson score.

Fig 14 · Interactive
01 / 11

Three jobs, one CPU

Three jobs, A, B and C, arrive together at time 0. Each needs 5 ms of CPU time. They wait in the ready queue, the line of jobs ready to run. The CPU can run only one at a time.

job   arrives   needs
A     0 ms      5 ms of CPU
B     0 ms      5 ms of CPU
C     0 ms      5 ms of CPU

ready queue   head -> A  B  C <- tail
CPU           one job at a time

response time    = first run - arrival
turnaround time  = finish    - arrival
Loading figure…
or ← →
Read the lesson step by step
  1. Three jobs, one CPU

    Three jobs, A, B and C, arrive together at time 0. Each needs 5 ms of CPU time. They wait in the ready queue, the line of jobs ready to run. The CPU can run only one at a time.

    job   arrives   needs
    A     0 ms      5 ms of CPU
    B     0 ms      5 ms of CPU
    C     0 ms      5 ms of CPU
    
    ready queue   head -> A  B  C <- tail
    CPU           one job at a time
    
    response time    = first run - arrival
    turnaround time  = finish    - arrival
  2. Running each to the end

    First come, first served runs A to the end, then B, then C. Shortest job first picks the same order here, since the jobs are equal. C waits 10 ms before it first runs. Average response time: 5 ms.

    timeline   AAAAABBBBBCCCCC
    
    job   first run   finish
    A      0 ms        5 ms
    B      5 ms       10 ms
    C     10 ms       15 ms
    
    average response    (0 + 5 + 10) / 3 = 5 ms
    average turnaround  (5 + 10 + 15) / 3 = 10 ms
  3. The time slice

    Round robin gives each job a short turn, a time slice (or quantum), here 1 ms. A hardware timer interrupts the CPU at a steady rate, so the kernel gets control back when the slice is used up.

    time slice (quantum)   q = 1 ms
    timer                  hardware; raises an interrupt
                           when the slice is over
    
    the slice is a whole number of timer periods
    (OSTEP: timer every 10 ms -> slice 10, 20, ... ms)
  4. Take the head of the queue

    The scheduler takes the job at the head of the queue, A, and starts it on the CPU. B and C each move up one place.

    line 1   job = queue.popleft()
    
    queue    A  B  C   ->   B  C
    CPU      idle      ->   A   (5 ms left)
    time     0 ms      A first runs: response 0 ms
  5. The timer fires

    A runs for 1 ms, then the timer interrupts. The interrupt forces the CPU back into the kernel, even though A never asked to stop. A has 4 ms of work left.

    line 2   run(job, SLICE)
    
    0 -> 1 ms   A runs
    1 ms        timer interrupt: CPU enters the kernel
              A: 5 ms -> 4 ms left
    
    A did not stop by itself: it was preempted
  6. Back of the line

    A still has work, so the kernel saves A's registers and puts A at the back of the queue. Then it loads B's registers and B starts its slice. This swap is a context switch.

    line 3   if job.left > 0:       A has 4 ms left: yes
    line 4   queue.append(job)
    
    save     A's registers
    queue    B  C  ->  C  A      (B taken from the head)
    load     B's registers;  B runs from 1 ms
  7. Everyone gets a turn

    B runs 1 ms, then C runs 1 ms. By 3 ms every job has started: response times 0, 1 and 2 ms, average 1 ms. With n jobs, none waits more than (n - 1) × slice = 2 ms for a turn.

    timeline   ABC
    
    job   first run
    A     0 ms
    B     1 ms
    C     2 ms
    
    average response   (0 + 1 + 2) / 3 = 1 ms
    longest wait       (3 - 1) x 1 ms = 2 ms
  8. Round and round

    The timer keeps ending turns: A, B, C, A, B, C... A finishes at 13 ms, B at 14 and C at 15. A job with no work left leaves the queue for good. Average turnaround time: 14 ms.

    timeline   ABCABCABCABCABC
    
    job   finish
    A     13 ms
    B     14 ms
    C     15 ms
    
    average turnaround  (13 + 14 + 15) / 3 = 14 ms
    a job whose work ends with its slice exits by itself;
    the timer does not need to fire
  9. The trade-off

    Round robin: response 1 ms, turnaround 14 ms. Running each to the end: response 5 ms, turnaround 10 ms. Sharing the CPU fairly makes every job start sooner but finish later.

                       response   turnaround
    run to the end     5 ms       10 ms
    round robin        1 ms       14 ms
    
    the same rule as a Python simulation:
    
    from collections import deque
    
    def round_robin(jobs, q):
        queue = deque(jobs.items())        # (name, work left), head first
        t, first, done, order = 0, {}, {}, ""
        while queue:
            name, left = queue.popleft()   # take the head of the queue
            first.setdefault(name, t)      # its first moment on the CPU
            run = min(q, left)             # one slice, or less to finish
            t += run
            order += name * run
            if left > run:
                queue.append((name, left - run))   # back of the line
            else:
                done[name] = t
        return order, first, done
    
    for q in (1, 5):
        order, first, done = round_robin({"A": 5, "B": 5, "C": 5}, q)
        print(q, order, sum(first.values()) / 3, sum(done.values()) / 3)
    
    prints:
    1 ABCABCABCABCABC 1.0 14.0
    5 AAAAABBBBBCCCCC 5.0 10.0
  10. How long a slice?

    Every switch costs time. With a 10 ms slice and a 1 ms switch, about a tenth of the CPU is lost; a 100 ms slice loses under 1%. But a very long slice turns round robin back into first come, first served.

    switch cost 1 ms     slice    lost to switching
                         1 ms     50.0%
                         10 ms    9.1%
                         100 ms   1.0%
    
    too short   switching eats the CPU
    too long    jobs wait: response time suffers
                (slice >= every job: FCFS again)
    typical today: 10 ms to 100 ms (Berkeley CS162)
  11. Round robin in Linux

    Linux offers round robin as the real-time policy SCHED_RR. Its slice defaults to 100 ms; sched_rr_get_interval() reads it. Ordinary programs use a fair-share scheduler instead, covered in the lesson "Fair-share scheduling and Linux CFS".

    C99 / POSIX, Linux (run with privilege):
    
    #define _POSIX_C_SOURCE 200809L
    #include <sched.h>
    #include <stdio.h>
    #include <time.h>
    
    int main(void) {
        struct sched_param p = { .sched_priority = sched_get_priority_min(SCHED_RR) };
        if (sched_setscheduler(0, SCHED_RR, &p) == -1) {   /* refused in this run */
            perror("sched_setscheduler");
            return 1;
        }
        struct timespec ts;
        if (sched_rr_get_interval(0, &ts) == -1) {
            perror("sched_rr_get_interval");
            return 1;
        }
        printf("time slice: %ld ms\n", (long)(ts.tv_sec * 1000 + ts.tv_nsec / 1000000));
        return 0;
    }
    
    prints   time slice: 100 ms
             (/proc/sys/kernel/sched_rr_timeslice_ms)
    no permission in this run: sched_setscheduler: Operation not permitted

Quiz Unlocks after the last step.