Lesson 6 of 26 · 13 min read
MLFQ, proportional share, and multicore scheduling
See how real schedulers learn job behavior without an oracle, assign proportional shares with lottery or stride tickets, and scale across multiple CPU cores.

Course syllabus · lesson 6 of 26
In this lesson
OSTEP Chapter 8 crux — How to schedule without perfect knowledge? How can the scheduler give interactive jobs short response times and short jobs good turnaround when their lengths are unknown? Chapter 9 crux — How to share the CPU proportionally. How can a scheduler allocate CPU time according to relative weights? Chapter 10 crux — How to schedule jobs on multiple CPUs. What new problems arise when the scheduler must choose both a job and a core?
Each question adds a different obligation. A shell waking after a keypress benefits from immediate CPU service. Two continuously runnable tenants can need specified shares over an interval. A worker moving between cores may lose useful cached state. Track response, actual CPU service, and core placement separately when judging the policies below.
Watch a job move through MLFQ
Step 1 of 4
Admit a new job
A new CPU-bound job starts at highest priority so a short or interactive job can get service quickly.
MLFQ learns from CPU consumption
A Multi-Level Feedback Queue has several ready queues with fixed relative priority. In a three-level system, Q2 has highest priority and Q0 has lowest. The dispatcher selects the highest nonempty queue. Within a level, ready jobs rotate in Round Robin order. New jobs start at the top because their behavior is still unknown. A job that uses its level's CPU allotment drops a level. At regular intervals the policy boosts all jobs to the top. These are the refined rules from Chapter 8.
A concrete implementation needs FIFO head and tail pointers for each level, ready links for each enqueued job, a current priority, and CPU budget fields in each job record. Quantum is the maximum CPU time for one turn. Allotment is the cumulative CPU time the job can consume at that level before demotion. With a 2 ms quantum and a 4 ms allotment, two full turns consume the budget. A job that runs for 1 ms and blocks has consumed 1 ms of its allotment. Sleep time consumes no CPU budget, and sleeping preserves the allotment already spent.
A scheduler can keep a next-boost deadline measured in elapsed time. Once it reaches the deadline, it accounts for execution up to that point, moves ready jobs to the highest priority, and refreshes their budgets. A blocked job's level and budget are refreshed too, but it joins the ready queue only on wakeup. The running job must also get the refreshed budget and participate in the new queue order. An implementation can track a boost epoch and update a sleeping job on wakeup. That produces the same priority reset without searching all sleepers at the deadline.
Periodic boosts let a ready job escape a lower queue that an endless supply of top-level arrivals would otherwise starve. Progress after a boost depends on the order in which those jobs enter and retain their place in the top queue. For example, consistent tail insertion for new jobs keeps later arrivals from jumping ahead of a boosted job. A very long period allows long delays, while an excessively short period can reset budgets before much feedback has accumulated. Keeping CPU charges across yields also closes the loophole in the earlier quantum-reset rule. A CPU-heavy job cannot extend its high priority indefinitely by blocking just before its turn ends.
The dispatch path below assumes execution is split at quantum, allotment, and boost boundaries. The outer scheduler handles the boost before selecting the next job. At the bottom level, budget exhaustion refreshes the same level rather than subtracting below zero.
job->slice_left -= ran;
job->allotment_left -= ran;
if (job->allotment_left == 0) {
if (job->level > 0)
--job->level;
job->allotment_left = allotment[job->level];
job->slice_left = quantum[job->level];
}
if (job->state == RUNNABLE)
enqueue_tail(&ready[job->level], job);
This fragment shows the charge and demotion path. If a job reaches the end of a slice with allotment left, the Round Robin path resets its slice for its next turn. A blocked job can also receive a fresh slice when it wakes in this model, capped by the existing allotment, and a job preempted by a higher-priority arrival can retain the unused part of its turn. Charge before testing the budget so the last bit of CPU time counts. Apply a demotion before enqueueing to avoid placing a job on the old queue under a new priority. Finally, check readiness so an exhausted budget does not accidentally requeue a blocked or finished job.
Lottery turns tickets into probabilities
With equal-length slices and a fixed runnable set, a job holding w of W runnable tickets has a probability w / W of winning each draw. Assign A 75 tickets and B 25, then draw one integer uniformly from 0 through 99. A owns the half-open range [0, 75) and B the range [75, 100). A linear scan can add each job's tickets and choose the first cumulative sum strictly greater than the winning number. Testing greater-than-or-equal would assign draw 75 to the wrong job. When no runnable job has tickets, there is no valid draw.
For sample draws 74, 75, 2, 98, 0, 10, 40, 80, the winners are A, B, A, B, A, A, A, B. A receives five of eight turns, even though its expectation is 8 * 0.75 = 6. For independent draws, the variance of A's number of wins is N * p * (1 - p). With N = 8 and p = 0.75, the variance is 1.5 wins squared. The variability in the observed fraction shrinks as the number of draws grows. A ticket ratio gives a long-run tendency under these assumptions and no bound on a particular unlucky wait.
A runnable-list implementation stores each job's weight and maintains the current total. Blocking or waking a job changes that denominator. If B sleeps, A has 75 of 75 runnable tickets, so it gets every available turn. A ticket transfer can let a server run with a client's weight while the client is waiting for its answer. Currency can group local ticket allocations under a global budget. In all cases proportionality depends on which weights participate in the draw and what CPU time each turn consumes.
Stride measures normalized service
Stride scheduling replaces the draw with a per-job increment. Choose a large constant L and set stride = L / tickets. Keep a pass value for each job. Select the smallest pass, run one full turn in this model, and then add that job's stride to its pass. More tickets mean a smaller increment, so the job returns to the minimum more often. Once jobs have similar passes, turns * L / tickets is similar across jobs. This explains why the ratio of turns follows the ratio of tickets. A min-heap keyed by pass can replace a full scan when the runnable set grows.
For dynamic membership, initializing every new job at zero can put a late arrival far behind in pass and allow it to dominate until it catches up. A simple admission rule for this model initializes it near the current minimum. A waking job also needs a defined rule about how much prior credit it retains. Integer rounding can distort shares, and L must be large enough to avoid zero strides under integer division. Long-lived pass counters require enough range or periodic normalization. Subtracting the same common offset from every pass preserves the ordering.
Global dispatch and per-core queues
Single-queue multiprocessor scheduling, or SQMS, lets each idle core take eligible work from a shared ready queue. With three independent ready workers and two idle cores, the cores can each take one and the third stays queued. A synchronized pop prevents both cores from claiming the same worker. As more cores enqueue and dequeue, contention for the queue lock and cache line can limit throughput. A global queue can use an affinity-aware selection policy, but a simple next-job rule may migrate a worker even if it has cache state on the previous core.
A core's caches can retain instructions and data from a worker's recent execution. On another core, some of those accesses may miss in its private caches or translations may need to be reestablished. Hardware coherence maintains a consistent memory view. It cannot make each core's cache already warm. Affinity trades that potential migration cost against the delay of leaving work queued on a busy core.
Multi-queue multiprocessor scheduling, or MQMS, gives each core a local ready queue and generally a local lock. Different cores can dispatch from different queues concurrently. A worker can stay on the same core across slices. The failure mode is imbalance: one core can sit idle while another has multiple runnable jobs. For instance, place two CPU-bound jobs on core 0 and none on core 1. Local Round Robin lets each get roughly half a core. Migrating one worker lets both use a full core after paying any migration cost.
In an illustrative work-stealing policy an idle core selects a victim, checks that it has queued eligible work, and moves a ready job to the idle core. The transfer must remove it from the victim queue before publishing it in the destination queue. The synchronization protocol must stop two thieves from moving the same job and avoid deadlock, for example by using a consistent lock order if holding both queue locks. A running job and a job pinned to the victim are ineligible for this kind of steal. A scheduler can also balance periodically when both cores have work but one has a larger backlog. Checking too often adds contention and migrations. Checking too rarely wastes available CPU service.
Worked trace
MLFQ. Use Q2 with a 2 ms quantum and 4 ms allotment, Q1 with a 4 ms quantum and 8 ms allotment, and lowest level Q0. Boost at elapsed time 16 ms. One job arrives at 0 and needs more than 16 ms of CPU. It runs on [0, 2) and on [2, 4), with Q2 budget 2 and then 0. It drops to Q1 and takes two 4 ms turns, on [4, 8) and [8, 12). It spends [12, 16) at Q0. At 16 ms the boost restores Q2 and gives it a fresh 4 ms allotment. A boost changes eligibility and future budget. It does not undo the earlier CPU charges.
Stride. Use L = 10000, tickets 100, 50, 250 for A, B, C, and strides 100, 200, 40. All passes start at zero and ties follow name order. Each row shows the chosen job and the three passes after charging it.
Turn Job A B C
1 A 100 0 0
2 B 100 200 0
3 C 100 200 40
4 C 100 200 80
5 C 100 200 120
6 A 200 200 120
7 C 200 200 160
8 C 200 200 200
The first eight dispatches give A two turns, B one, and C five, matching the ratio 2 : 1 : 5. The passes meet again at 200, so with unchanged jobs and tie-breaking, the same cycle repeats. An arbitrary prefix need not have exactly that ratio.
Change one input
In the MLFQ trace, let the job sleep for 2 ms immediately after its third millisecond of CPU service. Its top-level budget is then 1 ms. It wakes at time 5 and runs on [5, 6) before demotion. It reaches Q0 at time 14 and is still boosted at 16. Which clock moved? The CPU budget was exhausted 2 ms later in wall time, while the wall-time boost deadline stayed fixed.
Next, start address spaces and the C memory API.
Before you move on
Try it in your workspace
Sketch how MLFQ demotes a CPU-bound job that uses its full allotment at each queue level, then predict how a periodic priority boost and gaming-resistant accounting prevent starvation.
Keep a short note of what you tried, what passed, and what you still need to check.
0 of 3 checked.
Saved in this browser when storage is available. Uncheck any item to revisit it. This is your own record, not an assessment.