ENع
→Multi-level feedback queue
الدرس 15 · CPU scheduling

The multi-level feedback queue

لم يُترجم بعد؛ يُعرض باللغة الإنجليزية

14 دقيقة10 خطوات5 أسئلةIntermediate
عن هذا الدرس

Shortest job first gives great turnaround times, but only if the scheduler knows how long each job will run, and it never does. Round robin answers quickly but drags every job out. The multi-level feedback queue (MLFQ) gets close to both by watching how jobs behave: new jobs start at top priority, jobs that use up their time sink to lower queues with longer slices, and a periodic boost lifts everyone back up. Follow three jobs, one long, one interactive and one short, through a 1 ms simulation of the five MLFQ rules. The lessons on first come first served and shortest job first, and on round robin and the time slice, are the background; the context switch from the processes module is what happens each time a job leaves the CPU.

ستتعلّم

حدّد ما تشعر بأنك أتقنته. هذا التقييم الذاتي لا يؤثر في درجة الدرس.

شكل 15 · تفاعلي
01 / 10

Queues by priority

The scheduler cannot know how long a job will run. MLFQ keeps several ready queues, one per priority. Rule 1: a job in a higher queue runs first. Rule 2: jobs in the same queue take turns, round robin.

queue   priority   time slice (= allotment)
Q2      top        10 ms
Q1      middle     20 ms
Q0      bottom     40 ms

Rule 1  higher queue runs first
Rule 2  same queue: round robin, using that queue's slice

one CPU core: one job runs at a time
جارٍ تحميل الرسم…
أو ← →
اقرأ الدرس خطوة بخطوة
  1. Queues by priority

    The scheduler cannot know how long a job will run. MLFQ keeps several ready queues, one per priority. Rule 1: a job in a higher queue runs first. Rule 2: jobs in the same queue take turns, round robin.

    queue   priority   time slice (= allotment)
    Q2      top        10 ms
    Q1      middle     20 ms
    Q0      bottom     40 ms
    
    Rule 1  higher queue runs first
    Rule 2  same queue: round robin, using that queue's slice
    
    one CPU core: one job runs at a time
  2. New jobs start at the top

    Job A arrives at 0 ms. Rule 3: every new job starts in the top queue, because it might be short. Nothing else is waiting, so A goes straight onto the CPU.

    Rule 3  a new job enters the top queue
    
    job A   a long CPU-bound job
    t = 0 ms   A enters Q2, then runs (Q2 slice 10 ms)
  3. Used it all: down one

    A runs its whole 10 ms without stopping. Rule 4: a job that uses up its allotment at a level moves down one queue. So at 10 ms A drops to Q1, where the slice is 20 ms.

    Rule 4  allotment used up -> down one queue
    
    t = 0..10    A runs in Q2   used 10 of 10 ms
    t = 10       A drops to Q1, runs again (slice 20 ms)
    
    the scheduler learns from what the job does:
    it used all its time, so it may be a long job
  4. Long jobs sink

    A uses all 20 ms in Q1 too, so at 30 ms it sinks to Q0, the bottom. Down here the slice is 40 ms: long CPU-bound jobs switch less often, which wastes less time on context switches.

    t = 10..30   A runs in Q1   used 20 of 20 ms
    t = 30       A drops to Q0 (bottom), slice 40 ms
    
    low queues: long slices, few switches
    high queues: short slices, quick turns
  5. An interactive job arrives

    Job B arrives at 35 ms in Q2. Rule 1: it outranks A, so it runs at once. After 1 ms of work it waits for input and gives up the CPU. It keeps its place in Q2, and A runs again.

    job B   an interactive job: 1 ms of work, then 19 ms waiting for input
    t = 35       B enters Q2: preempts A (Rule 1)
    t = 35..36   B runs 1 ms, then waits for input
    t = 36       A runs again in Q0
    
    B as a real program (C99, POSIX):
    
    #define _POSIX_C_SOURCE 199309L
    #include <time.h>
    
    int main(void) {
        struct timespec io = { 0, 19000000 };   /* 19 ms */
        for (int i = 0; i < 8; i++) {
            volatile long x = 0;
            while (x < 100000) x++;            /* a short burst of work */
            nanosleep(&io, NULL);              /* block: give up the CPU */
        }
        return 0;
    }
  6. A short job gets in fast

    Short job C arrives at 40 ms. It starts in Q2, so it outranks A and runs at once. It uses its 10 ms allotment, so at 50 ms it moves down to Q1. Q2 is empty, so C keeps running.

    job C   a short 25 ms job
    t = 40       C enters Q2: preempts A
    t = 40..50   C runs in Q2   used 10 of 10 ms
    t = 50       C drops to Q1 and runs on
                 (B is still waiting, A is in Q0)
  7. Short jobs finish first

    At 55 ms B's input arrives; B outranks C and runs 1 ms. C then finishes at 66 ms, just 26 ms after it arrived, while A still waits. Without knowing job lengths, MLFQ behaves almost like shortest job first.

    t = 55       B back from I/O: preempts C, runs 1 ms
    t = 56..66   C runs in Q1, done at 66 ms
                 C waited 1 ms in total: turnaround 26 ms
    t = 66       A runs again in Q0
    
    short jobs finish while still high up;
    long jobs show themselves by sinking
  8. Every millisecond counts

    B returns every 20 ms to run 1 ms. Rule 4 counts it all: by 96 ms B has used 4 of its 10 ms in Q2. A job cannot stay on top by giving up the CPU just before its slice ends.

    t = 75, 95   B back from I/O, runs 1 ms, waits again
    B in Q2      used 1 + 1 + 1 + 1 = 4 of 10 ms
    
    gaming: run 9 ms, do a tiny I/O, repeat.
    If giving up the CPU reset the count, such a job
    would hold the top queue for ever. Rule 4 keeps
    the total, so after 10 ms it drops a level.
  9. The boost lifts everyone

    With many interactive jobs, A could starve in Q0. Rule 5: every S ms (here 100) the scheduler moves every job to the top queue. At 100 ms A is back in Q2 and runs. B is reset to Q2 too, though it still waits.

    Rule 5  every S = 100 ms: all jobs to the top queue
    
    t = 99       A used 40 of 40 ms in Q0 (stays at the bottom)
    t = 100      boost: A and B to Q2, counts reset
                 A runs in Q2 (B is still waiting for input)
    
    no starvation, and a job that turns interactive
    is treated as interactive again
  10. Learning from behaviour

    MLFQ watches what each job does instead of asking for its length. Short and interactive jobs stay high and answer quickly; long jobs sink and use long slices; the boost keeps everyone moving.

    the five rules as a Python simulation:
    
    SLICE = {2: 10, 1: 20, 0: 40}    # ms; allotment = slice
    jobs = {"A": [0, [400]], "B": [35, [1] * 8], "C": [40, [25]]}
    IO = 19                          # B waits 19 ms after each burst
    level, used, left, wake, done = {}, {}, {}, {}, set()
    run, log = None, []
    for t in range(101):
        if t == 100:                  # Rule 5: boost
            level = {j: 2 for j in level}; used = {j: 0 for j in used}
            run = None
        for j, (arrive, bursts) in jobs.items():
            if t == arrive:           # Rule 3: start at the top
                level[j], used[j], left[j], wake[j] = 2, 0, bursts[:], t
        ready = [j for j in level if wake[j] <= t and j not in done]
        top = max(level[j] for j in ready)
        if run not in ready or level[run] < top:   # Rule 1
            run = min((j for j in ready if level[j] == top), key=wake.get)
        if not log or log[-1][1] != (run, level[run]):
            log.append((t, (run, level[run])))
        used[run] += 1; left[run][0] -= 1
        if left[run][0] == 0:         # burst over: done, or wait for I/O
            left[run].pop(0)
            if not left[run]: done.add(run)
            else: wake[run] = t + 1 + IO
        if used[run] >= SLICE[level[run]]:   # Rule 4: down one level
            level[run], used[run] = max(0, level[run] - 1), 0
            wake[run] = t + 1         # to the back of its new queue
        if run in done or wake[run] > t + 1: run = None
    for t, (j, q) in log: print(t, f"{j}@Q{q}")
    
    prints who runs from each moment (ms):
    0 A@Q2
    10 A@Q1
    30 A@Q0
    35 B@Q2
    36 A@Q0
    40 C@Q2
    50 C@Q1
    55 B@Q2
    56 C@Q1
    66 A@Q0
    75 B@Q2
    76 A@Q0
    95 B@Q2
    96 A@Q0
    100 A@Q2

اختبار يتاح بعد الخطوة الأخيرة.