1. Understand the Goal: The user wants a "process scheduler" that supports "multiple scheduling policies." This is a classic operating systems concept.
-
Identify Key Components:
- Process (Task): Needs an ID, arrival time, burst time (execution time), priority (optional but good for Priority Scheduling), and state (waiting, running, finished). It also needs to track remaining time for preemptive algorithms.
- Scheduler Interface/Structure: A way to add processes and a way to run the simulation/execution loop.
- Scheduling Policies (Algorithms):
- First-Come, First-Served (FCFS): Non-preemptive, simple queue.
- Shortest Job First (SJF): Non-preemptive (usually), sort by burst time.
- Shortest Remaining Time First (SRTF): Preemptive version of SJF.
- Round Robin (RR): Preemptive, time quanta.
- Priority Scheduling: Preemptive or Non-preemptive.
- Output/Metrics: The user usually wants to see the Gantt chart (execution order) and metrics like Turnaround Time (TAT) and Waiting Time (WT).
-
Design the Architecture (Python):
- Class
Process: Stores attributes.
- Abstract Base Class
Scheduler: Defines add_process and run.
- Concrete implementations for each algorithm.
-
Refining the Scope:
- Writing a real OS scheduler is too complex and platform-dependent for a general request. I should simulate a scheduler.
- I need to choose a language. Python is readable and good for logic demonstration. C++ is faster and more "OS-like," but Python is better for explaining concepts. I'll stick with Python but structure it cleanly.
-
Developing the Algorithms (Mental Draft):
- FCFS: Sort by arrival time. Loop through list. Current time += burst.
- SJF (Non-preemptive): Sort by arrival. At every time step (or process completion), look for arrived processes, pick the one with the shortest burst time.
- Round Robin: Use a queue. Add arriving processes. Pop from front, run for
min(quantum, remaining), if not done, push back.
-
Drafting the Code Structure:
class Process:
def __init__(self, pid, arrival, burst, priority=0):
...
class Scheduler:
def __init__(self):
self.processes = []
self.timeline = [] # Gantt chart data
def add_process(self, p): ...
def run(self): ... # Abstract
-
Implementation Details & Edge Cases:
-
Time handling: In simulations, do we tick every millisecond, or jump to the next event? Jumping is faster, but ticking is easier to reason about for preemptive algorithms like Round Robin. I'll use an event-based loop where possible for efficiency, but a while loop with current_time is standard.
-
FCFS: Easy.
-
Round Robin: Needs a ready queue.
- Need to handle processes arriving while another is running.
- Need to handle the queue empty but processes still coming later (idle time).
-
Selecting the Policies to Implement:
To provide a "complete" answer, I should implement:
- FCFS (Baseline)
- SJF (Non-preemptive optimization)
- Round Robin (Time-sharing, preemptive)
- Priority (Preemptive is interesting, but let's stick to Non-preemptive for simplicity or add a flag. Let's do Preemptive Priority as it shows versatility).
-
Writing the Code (Iterative Refinement):
- The Process Class: Needs
remaining_time.
- Metrics: Calculate TAT (Completion - Arrival) and WT (TAT - Burst).
(Self-Correction during coding Round Robin): Handling the arrival of new processes during execution is tricky.
- Logic:
- Check for new arrivals at
current_time. Add to queue.
- If CPU is idle and queue is not empty, pop process.
- Execute for
quantum.
- Update
current_time.
- Check for arrivals again.
- If process finished, record completion time. Else, push back to queue.
-
Structuring the Final Output:
- Introduction: Briefly explain that this is a simulation.
- The Code: A single, clean, runnable Python script.
Process class.
Scheduler base class.
- Specific Schedulers (FCFS, SJF, RR).
- Main execution block to demonstrate.
- Explanation: How each works.
- Extension ideas: How to make it a real kernel module (briefly).
-
Refining the Code (Python):
- I will use a factory pattern or a Strategy pattern to switch policies.
- I'll create a
simulate function that takes a list of processes and a scheduler object.
Let's stick to a modular design.
Process: Data container.
Scheduler: Abstract class.
FCFSScheduler, RRScheduler, SJFScheduler.
Code Snippet logic for SJF:
Sort initially. Maintain a ready_queue. While uncompleted processes exist:
Add arrived to ready_queue.
If ready_queue empty: time jump to next arrival.
Else: Sort ready_queue by burst (or remaining burst), pick shortest.
Code Snippet logic for RR:
Use collections.deque.
-
Final Polish:
- Add comments.
- Add a print helper to visualize the output (Gantt chart style or stats table).
- Make sure variables are named clearly.
Self-Correction on Preemption: Implementing full preemption (SRTF or Preemptive Priority) complicates the loop significantly because you have to interrupt a running process if a new one with higher priority/shorter time arrives.
Decision: I will implement FCFS, SJF (Non-preemptive), and Round Robin. These cover the main types: simple, optimized for batch, and time-sharing. I will leave Priority for a mention or implement it if space permits. Actually, let's do Priority as well, it's easy to add once SJF is there.
-
Constructing the Response:
- Title: Process Scheduler Simulation.
- Code Block: Complete Python code.
- Walkthrough: Explain specific parts (Process class, the strategies).
- Example Output: Show what running it looks like.
(Self-Correction during drafting the code):
Make sure to deep copy processes for each simulation run, otherwise, the remaining_time modified by the RR scheduler will affect the SJF scheduler if run sequentially on the same objects.
Let's write the code mentally to ensure it runs.
process.remaining_time -= time_slice
If process.remaining_time <= 0: calculate stats.
Looks good. I will produce the Python solution.
Here is a complete, modular implementation of a Process Scheduler in Python.
This design uses a Strategy Pattern, where the scheduling logic is encapsulated in separate classes (FCFS, SJF, Round Robin) managed by a central Simulator. This allows you to easily add new policies without changing the core simulation loop.
The Python Implementation
import copy
from abc import ABC, abstractmethod
from collections import deque
# ==========================================
# 1. Data Structures
# ==========================================
class Process:
def __init__(self, pid, arrival_time, burst_time, priority=0):
self.pid = pid
self.arrival_time = arrival_time
self.burst_time = burst_time
self.priority = priority # Lower number = Higher priority
self.remaining_time = burst_time
# Metrics
self.start_time = -1
self.completion_time = 0
self.turnaround_time = 0
self.waiting_time = 0
self.response_time = -1
def __repr__(self):
return f"P{self.pid}"
# ==========================================
# 2. Scheduling Policies (Strategies)
# ==========================================
class Scheduler(ABC):
@abstractmethod
def add_process(self, process, current_time):
"""Add a process to the ready queue."""
pass
@abstractmethod
def get_next_process(self, current_time):
"""Retrieve the next process to run. Returns (process, time_slice)."""
pass
@abstractmethod
def is_preemptive(self):
"""Returns True if the scheduler can interrupt a running process."""
pass
class FCFSScheduler(Scheduler):
"""First-Come, First-Served. Non-preemptive."""
def __init__(self):
self.ready_queue = deque()
def add_process(self, process, current_time):
self.ready_queue.append(process)
def get_next_process(self, current_time):
if not self.ready_queue:
return None, 0
# Run until completion
return self.ready_queue.popleft(), float('inf')
def is_preemptive(self):
return False
class SJFScheduler(Scheduler):
"""Shortest Job First. Non-preemptive."""
def __init__(self):
self.ready_queue = []
def add_process(self, process, current_time):
self.ready_queue.append(process)
def get_next_process(self, current_time):
if not self.ready_queue:
return None, 0
# Sort by remaining time (which equals burst time for non-preemptive)
self.ready_queue.sort(key=lambda p: p.remaining_time)
return self.ready_queue.pop(0), float('inf')
def is_preemptive(self):
return False
class RRScheduler(Scheduler):
"""Round Robin. Preemptive based on Time Quantum."""
def __init__(self, time_quantum):
self.time_quantum = time_quantum
self.ready_queue = deque()
def add_process(self, process, current_time):
self.ready_queue.append(process)
def get_next_process(self, current_time):
if not self.ready_queue:
return None, 0
return self.ready_queue.popleft(), self.time_quantum
def is_preemptive(self):
return True
class PriorityScheduler(Scheduler):
"""Priority Scheduling. Non-preemptive (simple version)."""
def __init__(self):
self.ready_queue = []
def add_process(self, process, current_time):
self.ready_queue.append(process)
def get_next_process(self, current_time):
if not self.ready_queue:
return None, 0
# Sort by priority (Lower value = Higher priority)
self.ready_queue.sort(key=lambda p: p.priority)
return self.ready_queue.pop(0), float('inf')
def is_preemptive(self):
return False
# ==========================================
# 3. The Simulator (Engine)
# ==========================================
class Simulator:
def __init__(self, scheduler, processes):
self.scheduler = scheduler
# Deep copy to avoid modifying original data when running multiple sims
self.processes = copy.deepcopy(processes)
self.current_time = 0
self.timeline = [] # For logging execution flow
def run(self):
completed_processes = []
active_process = None
time_slice_remaining = 0
# Sort initial list by arrival time for processing
self.processes.sort(key=lambda p: p.arrival_time)
process_list_ptr = 0
while True:
# 1. Check for newly arriving processes
while (process_list_ptr < len(self.processes) and
self.processes[process_list_ptr].arrival_time <= self.current_time):
new_proc = self.processes[process_list_ptr]
self.scheduler.add_process(new_proc, self.current_time)
process_list_ptr += 1
# 2. Handle Preemption / Context Switching
# If CPU is idle OR current time slice expired (Round Robin)
if active_process is None or time_slice_remaining == 0:
# If the previous process didn't finish but time slice expired, put it back
if active_process and active_process.remaining_time > 0:
self.scheduler.add_process(active_process, self.current_time)
# Get next process from scheduler policy
active_process, time_slice_remaining = self.scheduler.get_next_process(self.current_time)
# Record first response time
if active_process and active_process.response_time == -1:
active_process.response_time = self.current_time
# 3. Exit Condition
if not active_process and process_list_ptr >= len(self.processes):
break
# 4. Execute Process
if active_process:
# Record start time
if active_process.start_time == -1:
active_process.start_time = self.current_time
# Simulate 1 unit of time
self.timeline.append((self.current_time, active_process.pid))
active_process.remaining_time -= 1
time_slice_remaining -= 1
self.current_time += 1
# Check for completion
if active_process.remaining_time == 0:
active_process.completion_time = self.current_time
active_process.turnaround_time = active_process.completion_time - active_process.arrival_time
active_process.waiting_time = active_process.turnaround_time - active_process.burst_time
completed_processes.append(active_process)
active_process = None # CPU becomes idle
else:
# CPU Idle: Jump to next process arrival
if process_list_ptr < len(self.processes):
self.current_time = self.processes[process_list_ptr].arrival_time
else:
break
return completed_processes
# ==========================================
# 4. Helper to Print Results
# ==========================================
def print_metrics(processes, policy_name):
print(f"\n--- Results for {policy_name} ---")
print(f"{'PID':<5} {'Arrival':<8} {'Burst':<6} {'Start':<6} {'Comp':<6} {'Turn':<6} {'Wait':<6} {'Resp':<6}")
avg_tat = 0
avg_wt = 0
processes.sort(key=lambda p: p.pid)
for p in processes:
print(f"{p.pid:<5} {p.arrival_time:<8} {p.burst_time:<6} {p.start_time:<6} "
f"{p.completion_time:<6} {p.turnaround_time:<6} {p.waiting_time:<6} {p.response_time:<6}")
avg_tat += p.turnaround_time
avg_wt += p.waiting_time
n = len(processes)
print(f"Average Wait: {avg_wt/n:.2f} | Average Turnaround: {avg_tat/n:.2f}")
# ==========================================
# 5. Main Execution
# ==========================================
if __name__ == "__main__":
# Define a common workload
workload = [
Process(pid=1, arrival_time=0, burst_time=5, priority=2),
Process(pid=2, arrival_time=1, burst_time=3, priority=1), # Shorter, Higher Priority
Process(pid=3, arrival_time=2, burst_time=8, priority=3),
Process(pid=4, arrival_time=3, burst_time=2, priority=4) # Shortest
]
# Test FCFS
sim_fcfs = Simulator(FCFSScheduler(), workload)
done_fcfs = sim_fcfs.run()
print_metrics(done_fcfs, "First-Come First-Served")
# Test SJF (Non-Preemptive)
sim_sjf = Simulator(SJFScheduler(), workload)
done_sjf = sim_sjf.run()
print_metrics(done_sjf, "Shortest Job First")
# Test Round Robin (Quantum = 2)
sim_rr = Simulator(RRScheduler(time_quantum=2), workload)
done_rr = sim_rr.run()
print_metrics(done_rr, "Round Robin (Q=2)")
# Test Priority
sim_pri = Simulator(PriorityScheduler(), workload)
done_pri = sim_pri.run()
print_metrics(done_pri, "Priority Scheduling")
Key Design Decisions
-
The Process Class:
- Tracks
remaining_time separately from burst_time. This allows the simulation to handle preemption (like Round Robin) where a process is paused and resumed later.
- Calculates standard metrics: Waiting Time, Turnaround Time, and Response Time.
-
The Strategy Interface (Scheduler):
- Defines how the simulator interacts with algorithms. The simulator doesn't care how the sorting works, only that it can
add_process and get_next_process.
get_next_process returns a tuple: (process, time_slice).
- For FCFS/SJF, the time slice is infinite (run until done).
- For Round Robin, it is fixed.
-
The Simulator Loop:
- It runs a "Tick-based" simulation (incrementing
current_time by 1). This is the most accurate way to simulate preemption.
- Arrival Handling: At every time step, it checks if new processes have arrived and adds them to the specific scheduler's ready queue.
- Preemption Logic: It checks if the
time_slice expired. If it did, it forces the CPU to ask for the next process, effectively putting the current one back in the queue (context switch).
Understanding the Algorithms Implemented
-
FCFS (First-Come, First-Served):
- Logic: A simple Queue (FIFO).
- Pros: Fair order of arrival.
- Cons: "Convoy Effect" — short processes wait behind long processes.
-
SJF (Shortest Job First):
- Logic: Sorts the waiting queue by
remaining_time. Picks the shortest.
- Note: This implementation is non-preemptive. If a short job arrives while a long one is running, it must wait for the long one to finish.
-
Round Robin:
- Logic: Uses a Queue with a Time Quantum.
- Pros: Fair time distribution; good for time-sharing systems.
- Cons: High overhead if quantum is too small; slow response if quantum is too large.
-
Priority Scheduling:
- Logic: Sorts by
priority attribute.
- Cons: Can lead to "Starvation" (low priority processes never run). A real-world implementation would need "Aging" (increasing priority of waiting processes over time), which is omitted here for simplicity.