TExcelTAD
Home › Operating Systems: Linux & Windows › Mini Project: Scheduler & Memory Simulator

Mini Project: Scheduler & Memory Simulator

In this project you'll build a small but complete simulation of the two jobs an operating system juggles all the time: sharing one CPU between several processes, and sharing a few page frames of RAM between their memory pages. You'll combine:

  • a Round Robin CPU scheduler with a time quantum (CPU Scheduling),
  • LRU page replacement over a shared pool of frames (Page Replacement),
  • a report with response, turnaround and waiting times, context switches and page-fault rates, and a comparison of different quantum and memory sizes.

Every step below is a complete program you can run and change. Later steps repeat the pieces they need, because each playground starts fresh.

Step 1: The workload

Each process has a name, an arrival time and a list of the pages it touches, one per CPU tick. The length of that list is the process's CPU burst, and its set of distinct pages is its working set. The names start with different letters, so the timeline can show one letter per tick.

python · try it yourself
WORKLOAD = [  # name, arrival, pages touched (one per CPU tick, so burst = number of pages)
    ("editor",   0, "E1 E2 E1 E1 E2 E1 E2 E2 E1 E3"),
    ("compiler", 1, "C1 C2 C1 C2 C3 C3 C1 C2 C3 C1 C2 C3"),
    ("browser",  2, "B1 B1 B2 B1 B2 B2"),
    ("zip",      4, "Z1 Z1 Z2 Z2 Z3 Z3"),
]

print(f"{'process':<9}{'arrival':>8}{'burst':>6}  working set")
total_pages = set()
for name, arrival, refs in WORKLOAD:
    pages = refs.split()
    total_pages |= set(pages)
    print(f"{name:<9}{arrival:>8}{len(pages):>6}  {' '.join(sorted(set(pages)))}")
print(f"total CPU work: {sum(len(r.split()) for _, _, r in WORKLOAD)} ticks, "
      f"distinct pages: {len(total_pages)}")
process   arrival burst  working set
editor          0    10  E1 E2 E3
compiler        1    12  C1 C2 C3
browser         2     6  B1 B2
zip             4     6  Z1 Z2 Z3
total CPU work: 34 ticks, distinct pages: 11

The zip process reads each page twice and then moves on (it streams through a file); the others keep returning to the same few pages, which is the locality that makes LRU work.

Step 2: Round Robin

Round Robin keeps a FIFO ready queue. The process at the front runs for at most quantum ticks; if it isn't finished, it goes to the back of the queue. Processes that arrive during a slice join the queue before the preempted process is put back, which is the usual convention.

We record three times per process:

  • response = first time on the CPU − arrival (how long until it reacts),
  • turnaround = finish − arrival,
  • waiting = turnaround − burst (time spent ready but not running).
python · try it yourself
from collections import deque

WORKLOAD = [
    ("editor",   0, "E1 E2 E1 E1 E2 E1 E2 E2 E1 E3"),
    ("compiler", 1, "C1 C2 C1 C2 C3 C3 C1 C2 C3 C1 C2 C3"),
    ("browser",  2, "B1 B1 B2 B1 B2 B2"),
    ("zip",      4, "Z1 Z1 Z2 Z2 Z3 Z3"),
]

def round_robin(quantum):
    arrivals = sorted((a, n, len(r.split())) for n, a, r in WORKLOAD)
    left = {n: b for _, n, b in arrivals}
    first, finish = {}, {}
    ready, time, timeline, switches, prev = deque(), 0, "", 0, None

    def admit():
        while arrivals and arrivals[0][0] <= time:
            ready.append(arrivals.pop(0)[1])

    admit()
    while ready or arrivals:
        if not ready:                      # CPU idle until the next arrival
            timeline += "-"
            time += 1
            admit()
            continue
        name = ready.popleft()
        switches += prev is not None and prev != name
        first.setdefault(name, time)
        run = min(quantum, left[name])
        for _ in range(run):
            timeline += name[0].upper()
            time += 1
            admit()
        left[name] -= run
        if left[name]:
            ready.append(name)
        else:
            finish[name] = time
        prev = name
    return timeline, first, finish, switches

timeline, first, finish, switches = round_robin(quantum=4)
print("timeline:", timeline)
print(f"{'process':<9}{'resp':>5}{'turn':>5}{'wait':>5}")
for name, arrival, refs in WORKLOAD:
    burst = len(refs.split())
    turn = finish[name] - arrival
    print(f"{name:<9}{first[name] - arrival:>5}{turn:>5}{turn - burst:>5}")
print("context switches:", switches)
timeline: EEEECCCCBBBBZZZZEEEECCCCBBZZEECCCC
process   resp turn wait
editor       0   30   20
compiler     3   33   21
browser      6   24   18
zip          8   24   18
context switches: 9

Read the timeline left to right: each letter is one tick of CPU time. Every process gets the CPU within a few ticks of arriving, which is Round Robin's strength.

Step 3: Choosing the quantum

The quantum is a trade-off. A tiny quantum gives quick response but many context switches (each one costs real time on a real CPU: saving registers, switching page tables, cold caches). A huge quantum degenerates into first-come, first-served. Let's charge each switch one tick of overhead and compare:

python · try it yourself
from collections import deque

WORKLOAD = [("editor", 0, 10), ("compiler", 1, 12), ("browser", 2, 6), ("zip", 4, 6)]

def round_robin(quantum, switch_cost=1):
    arrivals = sorted((a, n, b) for n, a, b in WORKLOAD)
    left = {n: b for _, n, b in arrivals}
    first, finish = {}, {}
    ready, time, switches, prev = deque(), 0, 0, None

    def admit():
        while arrivals and arrivals[0][0] <= time:
            ready.append(arrivals.pop(0)[1])

    admit()
    while ready or arrivals:
        if not ready:
            time += 1
            admit()
            continue
        name = ready.popleft()
        if prev is not None and prev != name:
            switches += 1
            time += switch_cost            # the dispatcher's overhead
            admit()
        first.setdefault(name, time)
        run = min(quantum, left[name])
        for _ in range(run):
            time += 1
            admit()
        left[name] -= run
        if left[name]:
            ready.append(name)
        else:
            finish[name] = time
        prev = name
    n = len(WORKLOAD)
    resp = sum(first[nm] - a for nm, a, _ in WORKLOAD) / n
    turn = sum(finish[nm] - a for nm, a, _ in WORKLOAD) / n
    return resp, turn, switches, time

print(f"{'quantum':>7}{'avg resp':>10}{'avg turn':>10}{'switches':>10}{'makespan':>10}")
for q in (1, 2, 4, 8, 16):
    resp, turn, switches, total = round_robin(q)
    print(f"{q:>7}{resp:>10.2f}{turn:>10.2f}{switches:>10}{total:>10}")
quantum  avg resp  avg turn  switches  makespan
      1      2.75     54.25        31        65
      2      3.50     39.00        15        49
      4      5.75     35.25         9        43
      8     11.25     30.25         5        39
     16     14.75     23.25         3        37

With quantum 1 the processes react fastest, but 31 of the 65 ticks (almost half the CPU time) go to switching. With quantum 16 every process (the longest burst is 12) finishes in its first slice: that is FCFS, with the best turnaround but the slowest response. Real kernels use slices of a few milliseconds, far longer than a context switch (a few microseconds), and Linux's EEVDF scheduler sizes them dynamically.

Step 4: LRU memory

Now the memory side. The machine has a small number of frames; each access either hits a page already in a frame or faults. On a fault with all frames full, LRU evicts the page that was used least recently. An OrderedDict keeps the pages in recency order:

python · try it yourself
from collections import OrderedDict

class LRUMemory:
    def __init__(self, frames):
        self.frames = frames
        self.pages = OrderedDict()          # oldest first, most recent last
        self.faults = self.hits = 0

    def access(self, page):
        if page in self.pages:
            self.pages.move_to_end(page)
            self.hits += 1
            return False
        self.faults += 1
        if len(self.pages) == self.frames:
            victim, _ = self.pages.popitem(last=False)
        self.pages[page] = True
        return True

mem = LRUMemory(3)
for page in "E1 E2 C1 E1 C2 E2 E1".split():
    fault = mem.access(page)
    print(f"{page}: {'fault' if fault else 'hit  '}  frames = {list(mem.pages)}")
print(f"faults {mem.faults}, hits {mem.hits}")

refs = "E1 E2 E1 E1 E2 E1 E2 E2 E1 E3 C1 C2 C1 C2 C3 C3 C1 C2 C3 C1 C2 C3".split()
for frames in (2, 3, 4, 6):
    m = LRUMemory(frames)
    for page in refs:
        m.access(page)
    print(f"{frames} frames: {m.faults:>2} faults out of {len(refs)} accesses")
E1: fault  frames = ['E1']
E2: fault  frames = ['E1', 'E2']
C1: fault  frames = ['E1', 'E2', 'C1']
E1: hit    frames = ['E2', 'C1', 'E1']
C2: fault  frames = ['C1', 'E1', 'C2']
E2: fault  frames = ['E1', 'C2', 'E2']
E1: hit    frames = ['C2', 'E2', 'E1']
faults 5, hits 2
2 frames: 12 faults out of 22 accesses
3 frames:  6 faults out of 22 accesses
4 frames:  6 faults out of 22 accesses
6 frames:  6 faults out of 22 accesses

Once the frames hold the working set of what's running (3 pages each for the editor and the compiler), only the unavoidable first-touch (compulsory) faults remain.

Step 5: Putting them together

Now the scheduler and the memory share one simulation. On every tick the running process touches its next page. A page fault means waiting for the disk; in this model the CPU simply stalls for fault_cost ticks (shown as * in the timeline). A real kernel would block the faulting process and run another one meanwhile; that's an extension at the end.

All processes share one global pool of frames, like Linux and Windows do for most memory.

python · try it yourself
from collections import OrderedDict, deque

WORKLOAD = [
    ("editor",   0, "E1 E2 E1 E1 E2 E1 E2 E2 E1 E3"),
    ("compiler", 1, "C1 C2 C1 C2 C3 C3 C1 C2 C3 C1 C2 C3"),
    ("browser",  2, "B1 B1 B2 B1 B2 B2"),
    ("zip",      4, "Z1 Z1 Z2 Z2 Z3 Z3"),
]

class LRUMemory:
    def __init__(self, frames):
        self.frames, self.pages = frames, OrderedDict()
        self.faults = self.hits = 0

    def access(self, page):
        if page in self.pages:
            self.pages.move_to_end(page)
            self.hits += 1
            return False
        self.faults += 1
        if len(self.pages) == self.frames:
            self.pages.popitem(last=False)
        self.pages[page] = True
        return True

def simulate(quantum, frames, fault_cost=2):
    mem = LRUMemory(frames)
    arrivals = sorted((a, n, r.split()) for n, a, r in WORKLOAD)
    pc = {n: 0 for n, _, _ in WORKLOAD}
    refs = {n: r.split() for n, _, r in WORKLOAD}
    ready, time, timeline = deque(), 0, ""

    def admit():
        while arrivals and arrivals[0][0] <= time:
            ready.append(arrivals.pop(0)[1])

    admit()
    while ready or arrivals:
        if not ready:
            timeline += "-"
            time += 1
            admit()
            continue
        name = ready.popleft()
        for _ in range(quantum):
            if mem.access(refs[name][pc[name]]):
                timeline += "*" * fault_cost      # stall while the page is read
                time += fault_cost
            timeline += name[0].upper()
            time += 1
            pc[name] += 1
            admit()
            if pc[name] == len(refs[name]):
                break
        if pc[name] < len(refs[name]):
            ready.append(name)
    return timeline, mem, time

for frames in (4, 12):
    timeline, mem, total = simulate(quantum=4, frames=frames)
    print(f"{frames} frames: {total} ticks, {mem.faults} faults")
    print("  " + timeline)
4 frames: 74 ticks, 20 faults
  **E**EEE**C**CCC**BB**BB**ZZ**ZZ**E**EEE**CC**C**C**BB**ZZ**E**E**C**C**CC
12 frames: 56 ticks, 11 faults
  **E**EEE**C**CCC**BB**BB**ZZ**ZZEEEE**CCCCBB**ZZE**ECCCC

With 4 frames the four processes keep evicting each other's pages: by the time the editor runs again, its pages are gone. This is thrashing in miniature. With 12 frames everything fits (there are 11 distinct pages), so only the 11 compulsory faults remain and the total time drops sharply.

Step 6: The final report

The finished simulator wraps everything into a Process class, collects per-process statistics, and prints a report for one configuration plus a comparison grid of quantum sizes and frame counts:

python · try it yourself
from collections import OrderedDict, deque

WORKLOAD = [
    ("editor",   0, "E1 E2 E1 E1 E2 E1 E2 E2 E1 E3"),
    ("compiler", 1, "C1 C2 C1 C2 C3 C3 C1 C2 C3 C1 C2 C3"),
    ("browser",  2, "B1 B1 B2 B1 B2 B2"),
    ("zip",      4, "Z1 Z1 Z2 Z2 Z3 Z3"),
]

class Process:
    def __init__(self, name, arrival, refs):
        self.name, self.arrival, self.refs = name, arrival, refs.split()
        self.pc, self.first_run, self.finish, self.faults = 0, None, None, 0

    @property
    def burst(self):
        return len(self.refs)

    @property
    def done(self):
        return self.pc == self.burst

class LRUMemory:
    def __init__(self, frames):
        self.frames, self.pages = frames, OrderedDict()
        self.faults = self.hits = 0

    def access(self, page):
        if page in self.pages:
            self.pages.move_to_end(page)
            self.hits += 1
            return False
        self.faults += 1
        if len(self.pages) == self.frames:
            self.pages.popitem(last=False)
        self.pages[page] = True
        return True

def simulate(quantum, frames, fault_cost=2):
    procs = [Process(*w) for w in WORKLOAD]
    mem = LRUMemory(frames)
    pending = sorted(procs, key=lambda p: p.arrival)
    ready, time, timeline, switches, prev = deque(), 0, "", 0, None

    def admit():
        while pending and pending[0].arrival <= time:
            ready.append(pending.pop(0))

    admit()
    while ready or pending:
        if not ready:
            timeline += "-"
            time += 1
            admit()
            continue
        p = ready.popleft()
        switches += prev is not None and prev is not p
        if p.first_run is None:
            p.first_run = time
        for _ in range(quantum):
            if mem.access(p.refs[p.pc]):
                p.faults += 1
                timeline += "*" * fault_cost
                time += fault_cost
            timeline += p.name[0].upper()
            time += 1
            p.pc += 1
            admit()
            if p.done:
                break
        if p.done:
            p.finish = time
        else:
            ready.append(p)
        prev = p
    return procs, mem, timeline, switches, time

def report(quantum, frames):
    procs, mem, timeline, switches, total = simulate(quantum, frames)
    accesses = mem.faults + mem.hits
    print(f"== Round Robin q={quantum}, LRU with {frames} frames ==")
    print("timeline:", timeline)
    print(f"{'process':<9}{'arr':>4}{'burst':>6}{'resp':>5}{'fin':>5}{'turn':>5}{'wait':>5}{'faults':>7}")
    for p in procs:
        turn = p.finish - p.arrival
        print(f"{p.name:<9}{p.arrival:>4}{p.burst:>6}{p.first_run - p.arrival:>5}"
              f"{p.finish:>5}{turn:>5}{turn - p.burst:>5}{p.faults:>7}")
    useful = sum(p.burst for p in procs)
    print(f"makespan {total} ticks, CPU doing useful work {useful / total:.0%}, "
          f"context switches {switches}")
    print(f"page faults {mem.faults} of {accesses} accesses ({mem.faults / accesses:.0%})")

report(quantum=4, frames=8)
print()
print(f"{'quantum':>7}{'frames':>7}{'makespan':>9}{'faults':>7}{'switches':>9}{'avg wait':>9}")
for q in (2, 4, 8):
    for f in (4, 8, 12):
        procs, mem, _, switches, total = simulate(q, f)
        avg_wait = sum(p.finish - p.arrival - p.burst for p in procs) / len(procs)
        print(f"{q:>7}{f:>7}{total:>9}{mem.faults:>7}{switches:>9}{avg_wait:>9.2f}")
== Round Robin q=4, LRU with 8 frames ==
timeline: **E**EEE**C**CCC**BB**BB**ZZ**ZZEEEE**CC**C**C**BB**ZZE**ECCCC
process   arr burst resp  fin turn wait faults
editor      0    10    0   58   58   48      3
compiler    1    12    7   62   61   49      5
browser     2     6   14   50   48   42      3
zip         4     6   20   54   50   44      3
makespan 62 ticks, CPU doing useful work 55%, context switches 9
page faults 14 of 34 accesses (41%)

quantum frames makespan faults switches avg wait
      2      4       84     25       15    57.25
      2      8       60     13       15    39.75
      2     12       56     11       15    37.75
      4      4       74     20        9    52.25
      4      8       62     14        9    45.75
      4     12       56     11        9    39.75
      8      4       64     15        5    40.25
      8      8       64     15        5    40.25
      8     12       56     11        5    37.75

How to read the report:

  • wait here includes the ticks the CPU stalled on page faults, because the process was not making progress.
  • More frames always helps (LRU never gets worse with more memory) until the working sets fit; after that, extra RAM is idle.
  • When memory is tight (4 frames), a larger quantum helps a lot: faults fall from 25 to 15, because each process uses its pages several times in a row before another process can evict them. With 8 frames the quantum hardly matters (13 to 15 faults), and with 12 not at all: once there is no competition for frames, scheduling and paging stop interfering.
  • The price of a large quantum is response time for interactive processes (the editor waits longer for its next turn), which is why real systems don't simply pick huge slices.

Ideas to extend it

  1. Block on faults: instead of stalling, move a faulting process to a blocked list for fault_cost ticks and run the next ready process. CPU utilisation should rise.
  2. Per-process frame limits (a local replacement policy, like Windows' working-set limits): give each process at most 3 frames and compare with the global pool.
  3. Other policies: swap Round Robin for SJF or a multilevel feedback queue, and LRU for FIFO or Clock (second chance), then compare the grids.
  4. Dirty pages: mark pages as written and charge an extra tick when a dirty page is evicted (it must be written to swap or the page file first).

Learn more: CPU Scheduling · Page Replacement · OS Exercises

Test yourself

In the simulator, what happens when the quantum is larger than every process's burst?

  1. The simulation never ends
  2. Round Robin behaves like first-come, first-served
  3. Every access becomes a page fault
  4. Response time drops to zero

Why does the total time fall sharply when the frames go from 4 to 12?

  1. The quantum changes
  2. All 11 distinct pages fit, so only compulsory faults remain and the processes stop evicting each other's pages
  3. LRU switches to FIFO
  4. Context switches disappear

What does an OrderedDict give the LRU implementation?

  1. Sorting by page name
  2. Recency order: move_to_end on a hit and popitem(last=False) to evict the least recently used page
  3. Thread safety
  4. Automatic page faults