Prac 301
Prac 301
Prac 301
Prac-2:
a. Write a program to work with a single thread
b. Write a program to work with multithreads
c. Write a program such that a multithreaded program generates a
fibonacci sequence
Prac-4:
a. Write a program that implements FCFS(First Come First Serve)
scheduling algorithm
Prac-5:
a. Write a program that implements SJF(with no preemption)
scheduling algorithm
Prac-6:
a. Write a program that implements RR scheduling algorithm
Prac-8:
a. Write a program that implements the FIFO page-replacement
algorithm
Prac-1:
b. Write a program to give a solution to the producer-consumer
problem using message passing
Q. Write a program to give a solution to the dining philosophers
problem
Prac-3:
b. Write a program to give a solution to the readers–writers problem
'''
# a. Write a program to work with a single thread
'''
import threading as t
def square(n):
print(f"The square of the number {n} is: {n**2}")
def cube(n):
print(f"The cube of the number {n} is: {n**3}")
if __name__=="__main__":
a=int(input("Enter the number for finding its square:"))
b=int(input("Enter the number for finding its cube:"))
t1=t.Thread(target=square(a))
t2=t.Thread(target=cube(b))
t1.start()
t2.start()
t1.join()
t2.join()
print("Program has ended..")
'''
# b. Write a program to work with multithreads
'''
import threading as t
def even(n):
print("Even numbers.." )
for x in range(0,n+1,2):
print(f"{x}..")
def odd(n):
print("Odd numbers..")
for y in range(1,n+1,2):
print(y)
if __name__=="__main__":
n=int(input("Enter the number till you want to display even and odd
numbers:"))
t1=t.Thread(target=even,args=(n,))
t2=t.Thread(target=odd,args=(n,))
t1.start()
t2.start()
t1.join()
t2.join()
print("Program has ended..")
'''
# c. Write a program such that a multithreaded program generates a
fibonacci sequence
'''
import threading as t
def disp(n):
if(n<0):
print("Please enter correct value..")
else:
print(f"The fibonacci series till the number {n} is: ")
def disp1(n):
for x in range(n+1):
print("fib{} = ".format(x))
def fib(n):
if(n==0):
print(0)
elif(n>0):
a=0
b=1
print(a)
print(b)
for x in range(2,n+1):
c=a+b
a=b
b=c
print(c)
if __name__=="__main__":
n=int(input("Enter the number for finding its fibonacci series:"))
t1=t.Thread(target=disp(n))
t2=t.Thread(target=disp1,args=(n,))
t3=t.Thread(target=fib,args=(n,))
t1.start()
t2.start()
t3.start()
t1.join()
t2.join()
t3.join()
print("Program has ended..")
'''
# a. Write a program that implements FCFS(First Come First Serve)
'''
import numpy as np
p=int(input("Enter the number of processes:"))
P=[]
arr_time=[]
bur_time=[]
comp_time=[0]*p
ta_time=[0]*p
wait_time=[0]*p
for x in range(p):
P.append("P{}".format(x+1))
for x in range(p):
a=int(input(f"Enter the arrival time for the process {P[x]}: "))
arr_time.append(a)
b=int(input(f"Enter the burst time for the process {P[x]}: "))
bur_time.append(b)
for x in range(p):
for y in range(x+1):
comp_time[x]+=bur_time[y]
for x in range(p):
ta_time[x]=comp_time[x]-arr_time[x]
for x in range(p):
wait_time[x]=ta_time[x]-bur_time[x]
avgwait_time=np.average(wait_time)
print("--------------------------------------------------------------------------------------
---------------------------------")
print("| Process | Arrival Time | Burst Time | Completion Time | Turn
Around Time | Waiting Time |")
print("--------------------------------------------------------------------------------------
---------------------------------")
for x in range(p):
print("|{}|{}|{}|{}|{}|
{}|".format(P[x].center(12),str(arr_time[x]).center(21),str(bur_time[x]).
center(18),str(comp_time[x]).center(27),str
(ta_time[x]).center(29),str(wait_time[x]).center(21)))
print("--------------------------------------------------------------------------------------
---------------------------------")
print("The average waiting time of the processes are: {}
milliseconds".format(avgwait_time))
'''
# a. Write a program that implements SJF(with no preemption)
scheduling algorithm
'''
import numpy
print("Program for Shortest Job First Scheduling Algorithm")
p=int(input("Enter the number of processes:"))
P=[]
arr_time=[]
bur_time=[]
b_time=0
comp_time=[0]*p
ta_time=[0]*p
wait_time=[0]*p
bt=[0]*p
z=[]
for x in range(1,p+1):
P.append("P{}".format(x))
for x in range(1,p+1):
a=int(input("Enter the arrival time for process P{} :".format(x)))
arr_time.append(a)
a=int(input("Enter the burst time for process P{} :".format(x)))
bur_time.append(a)
bt[x-1] = [bur_time[x-1], arr_time[x-1], x-1]
bt.sort(key=lambda x:x[1])
#bt.sort(key=lambda x:x[0]) #Use only if all the processes have arrival
time as 0
for i in range(sum(bur_time)): # Use range as (1,sum(bur_time)+1) if
arrival time starts from 1
list=[j for j in bt if j[1] <= i]
bt[bt.index(list[0])][0]-=1
for k in bt:
if (k[0]==0):
t=bt.pop(bt.index(k))
z.append([k, i + 1])
for x in range(len(bt)):
for y in range(x+1,len(bt)):
if(bt[x][0]>bt[y][0]):
bt[x],bt[y]=bt[y],bt[x]
for i in z:
comp_time[i[0][2]] = i[1]
for x in range(p):
ta_time[x]=comp_time[x]-arr_time[x]
for x in range(p):
wait_time[x]=ta_time[x]-bur_time[x]
avgwait_time=numpy.average(wait_time)
print("--------------------------------------------------------------------------------------
---------------------------------")
print("| Process | Arrival Time | Burst Time | Completion Time | Turn
Around Time | Waiting Time |")
print("--------------------------------------------------------------------------------------
---------------------------------")
for x in range(p):
print("|{}|{}|{}|{}|{}|
{}|".format(P[x].center(12),str(arr_time[x]).center(21),str(bur_time[x]).
center(18),str(comp_time[x]).center(27),str
(ta_time[x]).center(29),str(wait_time[x]).center(21)))
print("--------------------------------------------------------------------------------------
---------------------------------")
print("The average waiting time is: {}
milliseconds".format(avgwait_time))
'''
# a. Write a program that implements RR scheduling algorithm
'''
import numpy
print("Program for Round Robin Scheduling Algorithm")
p=int(input("Enter the number of processes:"))
P=[]
arr_time=[]
bur_time=[]
comp_time=[0]*p
ta_time=[0]*p
wait_time=[0]*p
bt=[0]*p
y=[]
bt1=[0]*p
for x in range(p):
P.append("P{}".format(x))
for x in range(1,p+1):
a=int(input("Enter the arrival time for process P{} :".format(x)))
arr_time.append(a)
a=int(input("Enter the burst time for process P{} :".format(x)))
bur_time.append(a)
bt[x-1] = [bur_time[x-1], arr_time[x-1], x-1]
bt1[x-1] = [bur_time[x-1], arr_time[x-1], x-1]
time_slice=int(input("Enter the time quantum for the processes:"))
for i in range(sum(bur_time)):
list=[j for j in bt if j[1] <= i]
c=list[0][2]
bt[bt.index(list[0])][0]-=1
b=bt[bt.index(list[0])][0]
for x in bt:
if(b==(bt1[c][0]-time_slice)):
if(bt1[c][0]!=time_slice):
bt1[c][0]=b
a=bt.pop(bt.index(x))
bt.insert(i+1,a)
break
if (x[0]==0):
bt.pop(bt.index(x))
y.append([x, i + 1])
for i in y:
comp_time[i[0][2]] = i[1]
for x in range(p):
ta_time[x]=comp_time[x]-arr_time[x]
for x in range(p):
wait_time[x]=ta_time[x]-bur_time[x]
avgwait_time=numpy.average(wait_time)
print("--------------------------------------------------------------------------------------
---------------------------------")
print("| Process | Arrival Time | Burst Time | Completion Time | Turn
Around Time | Waiting Time |")
print("--------------------------------------------------------------------------------------
---------------------------------")
for x in range(p):
print("|{}|{}|{}|{}|{}|
{}|".format(P[x].center(12),str(arr_time[x]).center(21),str(bur_time[x]).
center(18),str(comp_time[x]).center(27),str
(ta_time[x]).center(29),str(wait_time[x]).center(21)))
print("--------------------------------------------------------------------------------------
---------------------------------")
print("The average waiting time is: {}
milliseconds".format(avgwait_time))
'''
# a. Write a program that implements the FIFO page-replacement
algorithm
'''
a=list(map(int,input("Enter the string with page elements: ").split(',')))
page_frame=int(input("Enter the page frame for the string: "))
b=[None]*page_frame
page_hit=0
page_fault=0
for x in range(len(a)):
c=0
for y in range(page_frame):
if(a[x]==b[y]):
page_hit+=1
c=1
break
if(c==0):
if(x>page_frame-1):
del b[0]
b.append(a[x])
page_fault+=1
else:
b[x]=a[x]
page_fault+=1
print("Page Fault: ",page_fault)
print("Page Hit: ",page_hit)
'''
# b. Write a program to give a solution to the producer-consumer
problem using message passing
'''
from time import sleep
from random import random
from threading import Thread
from queue import Queue
def producer(queue):
print('Producer: Running')
for i in range(10):
value=random()
sleep(value)
item=(i,value)
queue.put(item)
print(f'>Producer added : {item}')
queue.put(None)
print('Producer : Done')
def consumer (queue):
print('Consumer : Running')
while True:
item=queue.get()
if item is None:
break
sleep(item[1])
print(f'>Consumer got : {item}')
print('Consumer : Done')
queue=Queue()
consumer=Thread(target=consumer,args=(queue,))
consumer.start()
producer=Thread(target=producer,args=(queue,))
producer.start()
producer.join()
consumer.join()
'''
# Q. Write a program to give a solution to the dining philosophers
problem
'''
import threading as t
import random
import time
class Philosopher(t.Thread):
running=True
def __init__(self,index,forkonleft,forkonright):
t.Thread.__init__(self)
self.index=index
self.forkonleft=forkonleft
self.forkonright=forkonright
def run(self):
while(self.running):
time.sleep(5)
print(f"Philosopher {self.index} is thinking...")
self.dine()
def dine(self):
fork1,fork2=self.forkonleft,self.forkonright
while self.running:
fork1.acquire()
locked=fork2.acquire(False)
if locked:
break
fork1.release()
print(f"Philosopher {self.index} swaps forks...")
fork1,fork2=fork2,fork1
else:
return
self.dining()
fork2.release()
fork1.release()
def dining(self):
print(f"Philosopher {self.index} starts eating...")
time.sleep(5)
print(f"Philosopher {self.index} finishes eating and leaves to
think...")
def main():
forks=[t.Semaphore() for n in range(5)]
philosophers=[Philosopher(i,forks[i%5],forks[(i+1)%5]) for i in
range(5)]
Philosopher.running=True
for p in philosophers:
p.start()
time.sleep(15)
Philosopher.running=False
print("Now we are finshing...")
if __name__=="__main__":
main()
'''
# Q. Write a program in python to give a solution to the race condition
by using Semaphores in an example
'''
from threading import Thread, Semaphore
from time import sleep
import sys
print=lambda x: sys.stdout.write("%s\n"%x)
playground=Semaphore(3)
def enter_playground(num):
global playground
print(f"Child {num+1} is waiting for his turn...")
playground.acquire()
print(f"\nChild {num+1} is playing...")
sleep(3)
print(f"\nChild {num+1} has left the playground...")
playground.release()
children=[]
for i in range(10):
children.append(Thread(target=enter_playground, args=(i,)))
children[i].start()
for i in range(10):
children[i].join()
'''
# b. Write a program to give a solution to the readers–writers problem
'''
import threading
import time
class ReaderWriter():
def __init__(self):
self.rd=threading.Semaphore()
self.wrt=threading.Semaphore()
self.readcount=0
self.exe=int(input("Enter the number of times the Read-Write
operation must be performed: "))
def reader(self):
for i in range(self.exe):
self.rd.acquire()
self.readcount+=1
if(self.readcount==1):
self.wrt.acquire()
self.rd.release()
print(f"Reader {self.readcount} is reading...")
self.rd.acquire()
self.readcount-=1
if(self.readcount==0):
self.wrt.release()
self.rd.release()
time.sleep(3)
def writer(self):
for i in range(self.exe):
self.wrt.acquire()
print("-"*20,"\nWriting Done\n"+"-"*20)
self.wrt.release()
time.sleep(3)
def main(self):
t=[]
a=input("Enter the Sequence for Readers and Writers:")
for i in range(len(a)):
x=[x for x in a]
if(x[i]=="R" or x[i]=="r"):
t.append(threading.Thread(target=self.reader))
t[i].start()
else:
t.append(threading.Thread(target=self.writer))
t[i].start()
for x in t:
x.join()
if __name__=="__main__":
c=ReaderWriter()
c.main()
'''