Linux CFS approximates an ideal fair scheduler using a red–black tree ordered by virtual runtime (vruntime).
// Tiny CFS-style simulator
class RBTLike { // use array sorted by key for simplicity
constructor() { this.a = []; }
insert(task) { this.a.push(task); this.a.sort((x,y)=>x.vr - y.vr); }
popMin() { return this.a.shift(); }
update(task) { this.insert(task); }
get size() { return this.a.length; }
}
function simulateCFS(tasks, slice=5, niceWeights={0:1.0}) {
// tasks: [{id, vr:0, weight:1.0, need: runtime}]
const runq = new RBTLike(); tasks.forEach(t=>runq.insert(t));
const log = [];
while (runq.size) {
const t = runq.popMin();
const actual = Math.min(slice, t.need);
t.need -= actual;
const invWeight = 1.0 / (t.weight || 1.0);
t.vr += actual * invWeight; // weighted fairness
log.push({id:t.id, ran:actual, vr:t.vr});
if (t.need > 0) runq.update(t);
}
return log;
}
// Sketch: queues[0..L-1], 0 is highest
function stepMLFQ(queues) {
for (let q=0; q0) queues[Math.min(q+1, queues.length-1)].push(t);
return t.id;
}
}
return null;
}