\$30.00

Category:

1. # [40 points] ProblemSet

1. ### [20 points] 5.10 Which of the following scheduling algorithms could result in starvation?Explain.

1. First-come,first-served

2. Shortest jobfirst

3. Roundrobin

4. Priority

2. [20 points] 5.12 Consider a system running ten I/O-bound tasks and one CPU-bound task. Assume that the I/O-bound tasks issue an I/O operation once for every millisecond of CPU computing and that each I/O operation takes 10 milliseconds to complete. Also assume that the context-switching overhead is 0.1 millisecond and that all processes are long-running tasks. Describe the CPU utilization fora

round-robin scheduler when:

1. The time quantum is 1millisecond

2. The time quantum is 10milliseconds

1. [60 points] ProgrammingExercise

In this programming exercise, you are to build a CPU scheduler that can compute the schedule for a variety of policies and calculate the various cost functions.

1. FIFO and PriorityQueue

A fundamental data structure in any CPU scheduler is a queue. Here, it can refer to a FIFO (first-in first-out) queue, but it may also refer to a priority queue, a LIFO (last-in first-out, also known as a stack), etc. Unlike random-access memory, where the reader or writer provides the memory address explicitly, a queue keeps track of its own addresses and provides only

.get()and.put()methods for reading and writing one element at a time.The following class is provided as an example:

———- file “fifo.py” ———-

classFIFO:

definit(self, initList=[]): self.A = list(initList)

defget(self): #remove elementandreturn itsevalue

returnself.A.pop(0) # throws underflow exception if empty

returnlen(self.A)andself.A[0]orNone

defiter(self): #iterator overitselements

foriinself.A: #convertabletotuple, list, for-in loop,etc

#### yieldi

deflen(self): #allows callertocall len(f) wheref isFIFO

returnlen(self.A)

defrepr(self): # shows a representation; we just show it as list

returnrepr(self.A)

### This will handle any data type. An example is (assume you save it in fifo.py)

>>>fromfifoimport*

>>>f =FIFO(range(3))

>>>f[0, 1,2]

>>>f.put(6)

>>>f.get()0

>>>len(f)3

### In addition, we also provide an implementation of a priority queue based on min-heap. You

don’t get the source code but you can import it from the minheap.pyc file provided: (updated 10/27 17:30)

minheap.pyc(for python 2.7.13)minheap.pyc(for python 3.5.2)minheap.pyc(for python 3.5.3)minheap.pyc(for python 3.6.2)

It has the following API:

——– file “minheap.py” ———–

classMinHeap:

definit(self):

deflen(self):

defiter(self):

defrepr(self):

defget(self):

defput(self, value):

defbuildheap(self): #reinitialize contentto beheapagain

### One difference is that your minheap data structure typecasts its elements to tuples before comparison, and Python will compare tuples in lexicographical order, and we will exploit this characteristic later when prioritizing tasks to run.

>>>fromminheapimportMinHeap

>>>h = MinHeap()

>>>foriin[(2,3), (3,4), (2,4), (4,5), (5, 6)]: h.put(i)

>>>h

[(2,3), (3, 4), (2, 4), (4, 5), (5,6)]

>>>h.get()(2, 3)

>>>h

[(2, 4), (3, 4), (5, 6), (4, 5)]

>>>h.get()(2, 4)

>>>h

[(3, 4), (4, 5), (5, 6)]

>>>h.put((6,7))

>>>h.get()(3, 4)

>>>h

[(5, 6), (4, 5), (6, 7)]

definit(self, name, release, cpuBurst):

# the task has a string name, release time and cpuBurst.

# the constructor may also need to initialize other fields,# forstatisticspurpose. Examplesinclude

# waiting time, remaining time, last dispatched time, and# completion time

defrepr(self):

# returns a string that looks like constructor syntax

returnself.class.name +'(%s,%d,%d)’%(repr(self.name),\self.release,self.cpuBurst)

defstr(self):

returnself.name

_KNOWN_SCHEMES = [“FCFS”, “SJF”, “RR”]

defsetPriorityScheme(self, scheme=”SJF”):”””

theschemecan be”FCFS”, “SJF”, “RR”,etc”””

self.scheme = scheme

if notscheme in _KNOWN_SCHEMES:

raiseValueError(“unknown scheme%s:mustbeFCFS, SJF,RR” %scheme)

defdecrRemaining(self):

# call this method to decrement the remaining time of this task

defremainingTime(self):

# returns the remaining time of this task

defdone(self):

# returns a boolean for if this task has remaining work to do

defsetCompletionTime(self, time):

# record the clock value when the task is completed

defturnaroundTime(self):

# returns the turnaround time of this task, as defined on# slide 10 of week 7 lecture

defincrWaitTime(self):

# increment the amount of waiting time for this task

defreleaseTime(self):

# returns the release time of this task

defiter(self):

# this enables converting the task into a tuple() type so that

# the priority queue can just cast it to tuple before comparison.# it depends on thepolicy

if(self.scheme == ‘FCFS’):

t =# your tuple that defines thepriority

elif(self.scheme==’SJF’):#shortestjobfirstt =# your tuple that defines thepriority

elif(self.scheme == ‘RR’): # round robin

t =# your tuple that defines the priority

#### else:

raiseValueError(“Unknown scheme %s” % self.scheme)

foriint:

#### yieldi

1. Nonpreemptive Scheduler (20points)

1. The NPScheduler class is instantiated with a policy and up to N time steps. Then the caller may add tasks to be scheduled, either as the scheduler runs or all at the beginning. The scheduler runs one time step at a time to fill in the Gantt chart with scheduled tasks. It also provides methods for the statistics. Use the following template (npsched-template.py, rename it asnpsched.py) to make your scheduler

fromfifoimportFIFO

fromminheapimportMinHeap

classNPScheduler: # nonpreemptive scheduler

definit(self, N, policy=’SJF’):

self.N=N #numberoftimestepstoscheduleself.running=None

self.clock=0 # thecurrent timestep beingscheduledself.policy=policy

# instantiate the readyQueue, which may be a FIFO or MinHeap# you may need additional queues for

# – tasks that have been added but not released yet# – tasks that have been completed

# – the Gantt chart

# if the release time of the new task is not in the future, then# put it in ready queue; otherwise, put into not-ready queue.

# you may need to copy the scheduler policy into the task

# dispatch here means assign the chosen task as the one to run# in the current time step.

# This method will make an entry into the Gantt chart and perform# bookkeeping, including

# – recording the last dispatched time of this task,

# – increment the wait times of those tasks not scheduled# but in the readyqueue

”’

whileTrue:

# assuming the not-Ready Queue outputs by release time

ifrisNoneorr.releaseTime() > self.clock:

#### break

# if there is a current running task, check if it has just finished.# (i.e., decrement remaining time and see if it has more work to do. # If so, perform bookkeeping for completing the task,

# – move task to done-queue, set its completion time and lastrun time# set the scheduler running task to None, and return True

# (so that a new task may be picked.)# but if not completed, return False.

# If there is no current running task, also return True.

ifself.runningisNone:

returnTrue

defschedule(self):

# scheduler that handles nonpreemptive scheduling.

# thepolicy suchas RR,SJF,orFCFSishandledby thetaskasit#definestheattributetocompare(in itsiter()method)

#Thereis acurrent running taskand it is notdoneyet!# the same task will continue running to its completion.# simply redispatch the current running task.

#### else:

# get the next task from priority queue and dispatch it.

defclockGen(self):

# this method runs the scheduler one time step at a time.

forself.clockinrange(self.N): # now run scheduler here self.schedule()

yieldself.clock

defgetSchedule(self):

return‘-‘.join(map(str, self.ganttChart))

scheduler = NPScheduler(nClocks, policy)

forclockinscheduler.clockGen():

#### print(‘nonpreemptive%s: %s’ %(scheduler.policy,scheduler.getSchedule()))

ifname ==’main‘:

5, 4)]]

forpolicyin[‘SJF’, ‘FCFS’, ‘RR’]:

(‘D’, 5, 4)]]

——— Your output would look like this:

\$python3 npscheduler.py

nonpreemptive SJF: A-A-A-A-A-A-A-C-B-B-B-B-D-D-D-D-None-None-None-None nonpreemptive FCFS:A-A-A-A-A-A-A-B-B-B-B-C-D-D-D-D-None-None-None-NonenonpreemptiveRR:A-A-A-A-A-A-A-B-B-B-B-C-D-D-D-D-None-None-None-None

1. ## Preemptive Scheduler (20points)

For this part, make a copy of your nonpreemptive scheduler and make it a preemptive one. The overall structure is the same as the Nonpreemptive scheduler.

——– file “psched-template.py”, rename and save as “psched.py”

classPScheduler(NPScheduler):#subclass from nonpreemptive scheduler#this meansit caninherit

defpreempt(self):

# this is the new method to add to put the running task

# back into ready queue, plus any bookkeeping if necessary.

#hint: comparebyfirst typecastingthetaskstotuple()first# andcompare themastuples. Thetuplesaredefinedin

# pick next task from ready queue to dispatch, if one exists.

#thisissameasbefore,butinstantiatethepreemptivescheduler.nClocks= 20

scheduler=PScheduler(nClocks,policy)# therestis thesameasbefore

forclockinscheduler.clockGen():

#### pass

print(‘preemptive %s: %s’ % (scheduler.policy, scheduler.getSchedule()))

ifname ==’main‘:

tasks = [Task(*i) for i in [(‘A’, 0, 7), (‘B’, 2, 4), (‘C’, 4, 1), (‘D’,

5, 4)]]

for policy in [‘SJF’, ‘FCFS’, ‘RR’]:

(‘D’, 5, 4)]]

preemptive SJF: A-A-B-B-C-B-B-D-D-D-D-A-A-A-A-A-None-None-None-None

preemptive FCFS: A-A-A-A-A-A-A-B-B-B-B-C-D-D-D-D-None-None-None-None

preemptie RR: A-A-B-A-B-C-A-D-B-A-D-B-A-D-A-D-None-None-None-None

### Implement the following methods to the nonpreemptive scheduler code (and the preemptive one will automatically get the same code due to inheritance).

defgetThroughput(self):

# throughput is the number of processes completed per unit time.

# returns a tuple for (number of done processes, number of clocks)

defgetWaitTime(self):

# returns a tuple for (total wait time of processes, #processes)

defgetTurnaroundTime(self):

# returns a tuple for (total turnaround times, #processes)

### Combine the nonpreemptive and preemptive schedulers into the same test bench and print out the statistics, so that the output looks like

\$python3hw6both.py

nonpreemptive SJF: A-A-A-A-A-A-A-C-B-B-B-B-D-D-D-D-None-None-None-None

 thruput = (4, 4) = 8.00 preemptive SJF: 16) =0.25, waittimes=(16,4) =4.00, turnaroundtime= A-A-B-B-C-B-B-D-D-D-D-A-A-A-A-A-None-None-None-None (32, thruput = (4, 16) =0.25, waittimes=(12,4) =3.00, turnaroundtime= (28,

4) = 7.00

nonpreemptive FCFS: A-A-A-A-A-A-A-B-B-B-B-C-D-D-D-D-None-None-None-None thruput= (4, 16) =0.25, waittimes=(19,4) =4.75, turnaroundtime=(35,

4) = 8.75

preemptive FCFS: A-A-A-A-A-A-A-B-B-B-B-C-D-D-D-D-None-None-None-None

thruput= (4, 16) =0.25, waittimes=(19,4) =4.75, turnaroundtime=(35,

4) = 8.75

nonpreemptiveRR:A-A-A-A-A-A-A-B-B-B-B-C-D-D-D-D-None-None-None-None thruput= (4, 16) =0.25, waittimes=(19,4) =4.75, turnaroundtime=(35,

4) = 8.75

preemptive RR: A-A-B-A-B-C-A-D-B-A-D-B-A-D-A-D-None-None-None-None

thruput= (4, 16) =0.25, waittimes=(22,4) =5.50, turnaroundtime=(38,

4) = 9.50