1(a).
Basic I/O programming- Process Creation
Program
# Python program for process creations
from multiprocessing import Process
import os
def info(title):
print(title)
print('module name:', __name__)
print('parent process:', os.getppid())
print('process id:', os.getpid())
def f(name):
info('function f')
print('hello', name)
if __name__ == '__main__':
info('main line')
p=Process(target=f, args=('bob',))
p.start()
p.join()
print("Child Process :",p.name)
print("Child Process ID:",p.pid)
Output
1(b). Basic I/O programming- File Operations
Program:
# Program to show various was to read and write data in a file.
# Open a file for Writing only
file1 = open("myfile.txt",'w')
# \n is placed to indicate EOL (End of Line)
file1.write("Hello \n")
file1.writelines(["This is Delhi \n","This is Paris \n","This is London \n"])
print()
file1.close() # to change file access modes
# Opens a file for both Reading and Writing a file
file1=open("myfile.txt",'r+')
print("Output of Read function is")
print(file1.read())
print()
# seek(n) takes the file handle to the nth bite from the beginning
file1.seek(0)
print("Output of Readline function is")
print(file1.readline())
print()
file1.seek(0)
# To show difference between read and readline
print("Output of Read(9) function is ")
print(file1.read(9))
print()
file1.seek(0)
# readlines function
print("Output of ReadLine function is")
print(file1.readlines())
print()
file1.close()
Output:
2. Shortest Job First Algorithm
Program:
# Python3 program for shortest Job first (Preemtive) algorithm
n = int(input('Enter no of processes: '))
bt = [0] * (n + 1)
at = [0] * (n + 1)
abt = [0] * (n + 1)
for i in range(n):
abt[i] = int(input('Enter the burst time for process {} : '.format(i + 1)))
at[i] = int(input('Enter the arrival time for process {} : '.format(i + 1)))
bt[i] = [abt[i], at[i], i]
bt.pop(-1)
print(abt)
print(bt)
sumbt = 0
i=0
ll = []
for i in range(0, sum(abt)):
l = [j for j in bt if j[1] <= i]
l.sort(key=lambda x: x[0])
bt[bt.index(l[0])][0] -= 1
for k in bt:
if k[0] == 0:
t = bt.pop(bt.index(k))
ll.append([k, i + 1])
ct = [0] * (n + 1)
tat = [0] * (n + 1)
wt = [0] * (n + 1)
for i in ll:
ct[i[0][2]] = i[1]
for i in range(len(ct)):
tat[i] = ct[i] - at[i]
wt[i] = tat[i] - abt[i]
ct.pop(-1)
wt.pop(-1)
tat.pop(-1)
abt.pop(-1)
at.pop(-1)
print('PNo\tBT\tAT\tCT\tTAT\tWT')
for i in range(len(ct)):
print("{}\t{}\t{}\t{}\t{}\t{}\n".format(i+1,abt[i], at[i], ct[i], tat[i], wt[i]))
print('Average Waiting Time = ', sum(wt)/len(wt))
print('Average Turnaround Time = ', sum(tat)/len(tat))
Output:
3. First Come First Served Algorithm
Program:
#Program for implementaion of FCFS Scheduling
def findWaitingTime(processes, n,bt, wt):
wt[0]=0
for i in range(1, n):
wt[i]=bt[i-1]+wt[i-1]
def findTurnAroundTime(processes, n,bt, wt, tat):
for i in range(n):
tat[i]=bt[i]+wt[i]
def findavgTime(processes, n, bt):
wt=[0]*n
tat=[0]*n
total_wt=0
total_tat=0
findWaitingTime(processes, n,bt,wt)
findTurnAroundTime(processes,n,bt,wt,tat)
print(" Processes"+" Burst time"+" Waiting time"+" Turn around time")
for i in range(n):
total_wt=total_wt+wt[i]
total_tat=total_tat+tat[i]
print(""+str(i+1)+"\t\t"+str(bt[i])+"\t"+str(wt[i])+"\t\t"+str(tat[i]))
print("Average Waiting time="+str(total_wt/n))
print("Average turn around time="+str(total_tat/n))
#Driver Code
if __name__ =="__main__":
processes=[1,2,3]
n=len(processes)
# Burst time of all processes
burst_time=[24,3,3]
findavgTime(processes,n,burst_time)
Output:
4a. Round Robin Scheduling Algorithm
Program:
#Python program for implementation of RR Scheduling
def findWaitingTime(processes,n,bt,wt,quantum):
rem_bt=[0]*n
for i in range(n):
rem_bt[i]=bt[i]
t=0 #Current time
while(1):
done=True
for i in range(n):
if (rem_bt[i]>0):
done=False # There is a pending process
if (rem_bt[i]>quantum):
t+=quantum
rem_bt[i]-=quantum
else:
t=t+rem_bt[i]
wt[i]=t-bt[i]
rem_bt[i]=0
if (done == True):
break
def findTurnAroundTime (processes, n, bt, wt,tat):
for i in range(n):
tat[i]=bt[i]+wt[i]
def findavgTime(processes, n, bt,quantum):
wt=[0]*n
tat=[0]*n
findWaitingTime(processes, n, bt,wt,quantum)
findTurnAroundTime(processes,n,bt,wt,tat)
#Display processes along with all details
print("Processes. \tBurst Time. \tWaiting Time. \tTurn-Around Time")
total_wt=0
total_tat=0
for i in range(n):
total_wt=total_wt+wt[i]
total_tat=total_tat + tat[i]
print("",i+1,"\t\t",bt[i],"\t\t", wt[i],"\t\t", tat[i])
print("\n Average waiting time=%.5f "%(total_wt / n))
print("Average turn around time=%.5f"% (total_tat / n))
#Driver code
if __name__=="__main__":
#Process id's
proc=[1,2,3]
n=3
# Burst time of all processes
#burst_time=[10,5,8]
burst_time=[24,3,3]
# Time quantum
quantum=4;
findavgTime(proc,n,burst_time,quantum)
Output:
4b. Priority Scheduling Algorithm
Program:
#Python Program for implementation of Priority Scheduling
def findWaitingTime(processes, n,wt):
wt[0]=0
for i in range(1,n):
wt[i]=processes[i-1][1]+wt[i-1]
def findTurnAroundTime(processes,n,wt,tat):
for i in range(n):
tat[i]=processes[i] [1]+wt[i]
def findavgTime (processes, n):
wt=[0]*n
tat=[0]*n
findWaitingTime(processes, n,wt)
findTurnAroundTime(processes, n, wt,tat)
print("\n Processes \t Burst Time \t Waiting","Time \t Turn-Around Time")
total_wt=0
total_tat=0
for i in range(n):
total_wt=total_wt+wt[i]
total_tat=total_tat+tat[i]
print("", processes[i][0], "\t\t",processes[i][1],"\t\t",wt[i],"\t\t",tat[i])
print("\n Average waiting time=%.5f"%(total_wt /n))
print("Average turn around time=", total_tat / n)
def priorityScheduling(proc, n):
#Sort processes by priority
proc=sorted(proc, key =lambda proc:proc[2], reverse=True);
print("Order in which processes gets executed")
for i in proc:
print(i[0], end="")
findavgTime(proc, n)
#Driver code
if __name__=="__main__":
# Process id's
proc=[[1,10,1],[2,5,0],[3,8,1]]
n=3
print("Priority Scheduling Algorithm")
priorityScheduling(proc, n)
Output:
5. To implement Reader/Writer problem using semaphore
Program
import threading
import time
class ReaderWriter():
def __init__(self):
self.rd = threading.Semaphore() #initializing semaphores using
#Semaphore class in threading module for reading and writing
self.wrt = threading.Semaphore()
self.readCount = 0 #initializing number of reader present
def reader(self):
while True:
self.rd.acquire() #wait on read semaphore
self.readCount+=1 #increase count for reader by 1
if self.readCount == 1: #since reader is present, avoid to write data
self.wrt.acquire() #wait on write semaphore
self.rd.release() #sinal on read semaphore
print("\n Reader is reading","\n",{self.readCount})
self.rd.acquire() #wait on read semaphore
self.readCount-=1 #reading performed by reader hence
decrementing readercount
if self.readCount == 0: #if no reader is present allow writer to write
self.wrt.release() #signal on write semphore, now writer can write
self.rd.release() #sinal on read semaphore
time.sleep(3)
def writer(self):
while True:
self.wrt.acquire() #wait on write semaphore
print("Wrting data.....") #write the data
print("-"*20)
self.wrt.release() #sinal on write semaphore
time.sleep(3)
def main(self):
#calling mutliple readers and writers
t1 = threading.Thread(target = self.reader)
t1.start()
t2 = threading.Thread(target = self.writer)
t2.start()
t3 = threading.Thread(target = self.reader)
t3.start()
t4 = threading.Thread(target = self.reader)
t4.start()
t6 = threading.Thread(target = self.writer)
t6.start()
t5 = threading.Thread(target = self.reader)
t5.start()
if __name__=="__main__":
c = ReaderWriter()
c.main()
Output:
6. Implement Banker’s algorithm for Deadlock avoidance
Program:
# Number of processes
P=5
# Number of resources
R=3
# Function to find the need of each process
def calculateNeed(need, maxm, allot):
# Calculating Need of each P
for i in range(P):
for j in range(R):
# Need of instance = maxm instance -
# allocated instance
need[i][j] = maxm[i][j] - allot[i][j]
# Function to find the system is in
# safe state or not
def isSafe(processes, avail, maxm, allot):
need = []
for i in range(P):
l = []
for j in range(R):
l.append(0)
need.append(l)
# Function to calculate need matrix
calculateNeed(need, maxm, allot)
# Mark all processes as infinish
finish = [0] * P
# To store safe sequence
safeSeq = [0] * P
# Make a copy of available resources
work = [0] * R
for i in range(R):
work[i] = avail[i]
# While all processes are not finished
# or system is not in safe state.
count = 0
while (count < P):
# Find a process which is not finish
# and whose needs can be satisfied
# with current work[] resources.
found = False
for p in range(P):
# First check if a process is finished,
# if no, go for next condition
if (finish[p] == 0):
# Check if for all resources
# of current P need is less
# than work
for j in range(R):
if (need[p][j] > work[j]):
break
# If all needs of p were satisfied.
if (j == R - 1):
# Add the allocated resources of
# current P to the available/work
# resources i.e. free the resources
for k in range(R):
work[k] += allot[p][k]
# Add this process to safe sequence.
safeSeq[count] = p
count += 1
# Mark this p as finished
finish[p] = 1
found = True
# If we could not find a next process
# in safe sequence.
if (found == False):
print("System is not in safe state")
return False
# If system is in safe state then
# safe sequence will be as below
print("System is in safe state.",
"\nSafe sequence is: ", end = " ")
print(*safeSeq)
return True
# Driver code
if __name__ =="__main__":
processes = [0, 1, 2, 3, 4]
# Available instances of resources
avail = [3, 3, 2]
# Maximum R that can be allocated
# to processes
maxm = [[7, 5, 3], [3, 2, 2], [9, 0, 2], [2, 2, 2], [4, 3, 3]]
# Resources allocated to processes
allot = [[0, 1, 0], [2, 0, 0], [3, 0, 2], [2, 1, 1], [0, 0, 2]]
# Check system is in safe state or not
isSafe(processes, avail, maxm, allot)
Output:
7. First In First Out Algorithm
Program:
from queue import Queue
# Function to find page faults using FIFO
def pageFaults(pages, n, capacity):
# To represent set of current pages.
# We use an unordered_set so that we
# quickly check if a page is present
# in set or not
s = set()
# To store the pages in FIFO manner
indexes = Queue()
# Start from initial page
page_faults = 0
for i in range(n):
# Check if the set can hold
# more pages
if (len(s) < capacity):
# Insert it into set if not present
# already which represents page fault
if (pages[i] not in s):
s.add(pages[i])
# increment page fault
page_faults += 1
# Push the current page into
# the queue
indexes.put(pages[i])
# If the set is full then need to perform FIFO
# i.e. remove the first page of the queue from
# set and queue both and insert the current page
else:
#Check if current page is not already present in the set
if (pages[i] not in s):
# Pop the first page from the queue
val = indexes.queue[0]
indexes.get()
# Remove the indexes page
s.remove(val)
# insert the current page
s.add(pages[i])
# push the current page into
# the queue
indexes.put(pages[i])
# Increment page faults
page_faults += 1
print(s,end=" ")
print("Page Fault Count",page_faults)
return page_faults
# Driver code
if __name__ == '__main__':
pages = [3,2,1,0,3,2,4,3,2,1,0,4]
n = len(pages)
capacity = 3
print("Total Page Fault Count",pageFaults(pages, n, capacity))
Output:
8. Least Recently Used Algorithm
Program:
capacity = 3
processList = [0,1,2,0,3,0,4,2,3,0,3,2]
# List of current pages in Main Memory
s = []
pageFaults = 0
# pageHits = 0
for i in processList:
# If i is not present in currentPages list
if i not in s:
# Check if the list can hold equal pages
if(len(s) == capacity):
s.remove(s[0])
s.append(i)
else:
s.append(i)
# Increment Page faults
pageFaults +=1
# If page is already there in
# currentPages i.e in Main
else:
# Remove previous index of current page
s.remove(i)
# Now append it, at last index
s.append(i)
print(s,end=" ")
print("Page Fault Count",pageFaults)
print("Total Page Faults",(pageFaults))
Output:
9(a). Implement First Fit algorithm for memory management
Program:
# Function to allocate memory to blocks as per First fit algorithm
def firstFit(blockSize, m, processSize, n):
# Stores block id of the block allocated to a process
allocation = [-1] * n
occupied=[False]*m
# Initially no block is assigned to any process
# pick each process and find suitable blocks
# according to its size ad assign to it
for i in range(n):
for j in range(m):
if not occupied[j] and blockSize[j] >= processSize[i]:
# allocate block j to p[i] process
allocation[i] = j
occupied[j]=True
# Reduce available memory in this block.
#blockSize[j] -= processSize[i]
break
print(" Process No. Process Size Block no.")
for i in range(n):
print(str(i + 1)+ " \t\t\t"+ str(processSize[i])+"\t\t\t", end = " ")
if allocation[i] != -1:
print(allocation[i] + 1)
else:
print("Not Allocated")
# Driver code
if __name__ == '__main__':
blockSize = [100, 50, 30, 120, 35]
processSize = [20, 60, 70, 40]
m = len(blockSize)
n = len(processSize)
firstFit(blockSize, m, processSize, n)
Output:
9.(b). Implementation of Best - Fit algorithm for memory
management
Program:
# Function to allocate memory to blocks
# as per Best fit algorithm
def bestFit(blockSize, m, processSize, n):
# Stores block id of the block
# allocated to a process
allocation = [-1] * n
# pick each process and find suitable
# blocks according to its size and
# assign to it
for i in range(n):
# Find the best fit block for current process
bestIdx = -1
for j in range(m):
if blockSize[j] >= processSize[i]:
if bestIdx == -1:
bestIdx = j
elif blockSize[bestIdx] > blockSize[j]:
bestIdx = j
# If we could find a block for current process
if bestIdx != -1:
# allocate block j to p[i] process
allocation[i] = bestIdx
# Reduce available memory in this block.
blockSize[bestIdx] -= processSize[i]
print("Process No. Process Size. \t Block no.")
for i in range(n):
print(i + 1, " \t\t", processSize[i], end = "\t\t")
if allocation[i] != -1:
print(allocation[i] + 1)
else:
print("Not Allocated")
# Driver code
if __name__ == '__main__':
blockSize = [100, 500, 200, 300, 600]
processSize = [212, 417, 112, 426]
m = len(blockSize)
n = len(processSize)
bestFit(blockSize, m, processSize, n)
Output:
9(c). Implement Worst fit algorithm for memory management
Program:
# Function to allocate memory to blocks as
# per worst fit algorithm
def worstFit(blockSize, m, processSize, n):
# Stores block id of the block
# allocated to a process
# Initially no block is assigned to any process
allocation = [-1] * n
# pick each process and find suitable blocks
# according to its size ad assign to it
for i in range(n):
# Find the best fit block for
# current process
wstIdx = -1
for j in range(m):
if blockSize[j] >= processSize[i]:
if wstIdx == -1:
wstIdx = j
elif blockSize[wstIdx] < blockSize[j]:
wstIdx = j
# If we could find a block for
# current process
if wstIdx != -1:
# allocate block j to p[i] process
allocation[i] = wstIdx
# Reduce available memory in this block.
blockSize[wstIdx] -= processSize[i]
print("Process No. \t Process Size. \t Block no.")
for i in range(n):
print(i + 1, "\t\t ",processSize[i], "\t\t",end = " ")
if allocation[i] != -1:
print(allocation[i] + 1)
else:
print("Not Allocated")
# Driver code
if __name__ == '__main__':
blockSize = [100, 500, 200, 300, 600]
processSize = [212, 417, 112, 426]
m = len(blockSize)
n = len(processSize)
worstFit(blockSize, m, processSize, n)
Output:
10. Inter Process Communiation with Shared memory
Program:
from multiprocessing import Process, Value, Array
def f(n,a):
n.value=3.1415927
for i in range(len(a)):
a[i]=-a[i]
if __name__=='__main__':
num=Value('d', 0.0)
arr=Array('i', range(10))
arr1=Array('i', range(1,20,2))
print("\t\t Inter Process Communication using Shared Memory")
p1=Process(target=f, args=(num, arr))
p1.start()
p1.join()
p2=Process(target=f, args=(num, arr1))
p2.start()
p2.join()
print(num.value)
print(arr[:])
print(arr1[:])
Output: