Skip to content

Instantly share code, notes, and snippets.

@benslv
Created May 6, 2020 10:07
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save benslv/84667dfeac3082b55612da0bae6f2a75 to your computer and use it in GitHub Desktop.
Save benslv/84667dfeac3082b55612da0bae6f2a75 to your computer and use it in GitHub Desktop.
Some scheduling algorithms
'''
FCFS Algorithm:
- Take process from front of priority queue.
- Let it execute until process terminates (i.e. for duration of process)
- Pop it from the queue and add to list of completed tasks.
- Repeat until zero processes left.
'''
def fcfs(queue, verbose=False):
completed = []
tick = 0
# Run until the queue is empty of processes.
while queue:
current_process = queue.pop(0)
if verbose:
print(current_process)
# Run each process until completion.
while current_process.duration > 0:
current_process.duration -= 1
tick += 1
# Once process is complete, push it to completed list.
completed.append(current_process)
print(tick)
return completed
queue = [Task("A", 10, 3), Task("B", 30, 2), Task("C", 5, 1)]
print(fcfs(queue))
'''
Round Robin Algorithm:
- Take process from front of priority queue.
- Decrement process duration and quantum.
- Increment tick.
- Check if process is complete (duration = 0)
- If so, push process to completed list.
- Check if quantum is zero (quantum = 0)
- If so, push process to back of queue.
'''
def round_robin(queue, verbose=False):
completed = []
tick = 0
# Run until queue is empty of processes.
while queue:
current_process = queue.pop(0)
quantum = 5
if verbose:
print(current_process)
# Each task has `quantum` ticks to run before being moved to the back.
while quantum > 0:
quantum -= 1
current_process.duration -= 1
tick += 1
# Check if process has completed.
if current_process.duration == 0:
completed.append(current_process)
break
# Only push the task back on the queue if its not complete.
if not current_process.duration == 0:
queue.append(current_process)
print(tick)
return completed
queue = [Task("A", 10, 3), Task("B", 30, 2), Task("C", 5, 1)]
print(round_robin(queue))
class Task:
def __init__(self, label, duration, priority):
self.label = label
self.duration = duration
self.priority = priority
def __str__(self):
return f"Task {self.label}\nDuration: {self.duration}\nPriority: {self.priority}"
def __repr__(self):
return str((self.label, self.duration, self.priority))
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment