Download as docx, pdf, or txt
Download as docx, pdf, or txt
You are on page 1of 31

S.I.E.

S College of Arts, Science and Commerce,


Sion(W), Mumbai – 400 022.

CERTIFICATE

This is to certify that Mr./ Miss. Rohit Sarvjeet Yadav has successfully completed

the necessary course of experiments in the subject of

Operating System during the academic year 2020 – 2021 complying with the

requirements of University of Mumbai, for the course of S.Y.BSc. Computer

Science [Semester-III ]

Head of the Department Prof. In-Charge (Computer


Science)

Date: 11/12/2020

College Seal
Sr. Practica Aim Date Page
No. l number
Number
1 1 Write a program to implement the 04/09/2020 03
concept of Remote Method
Invocation(RMI)
2 2 Programs to implement the concept 11/09/2020 05
of Multithreading
a. Program to display Summation of
numbers using thread
3 2 b. Program to display the prime 11/09/2020 07
numbers using thread
4 2 c. Program to display the Fibonacci 11/09/2020 08
series using thread
5 3 Write a program to implement 18/09/2020 09
Bounded Buffer to solve Producer
-Consumer problem with and without
Semaphore.
6 4 Write a program to simulate FCFS 09/10/2020 12
algorithm and calculate average
waiting time and average turnaround
time
7 5 Write a program to simulate SJF 16/10/2020 14
algorithm (Non pre-emptive) and
calculate average waiting time and
average turnaround time
8 6 Write a program to solve readers- 23/10/2020 16
writers problem.
9 7 Write a Python program that 06/11/2020 19
implements the banker’s algorithm.

Name: Rohit Yadav

Roll No: SCS2021103

Subject: Operating System

PRACTICAL NO-1

AIM: Write a program to implement the concept of Remote Method Invocation(RMI)


DESCRIPTION:

The Remote Method Invocation mechanism lets you do something that sounds simple. If
you have access to an object on a different machine, you can call methods of the remote
object. Of course, the method parameters must somehow be shipped to the other
machine, the object must be informed to execute the method, and the return value must
be shipped back. In RMI terminology, the object whose method makes the remote call is
called the client object. The remote object is called the server object. It is important to
remember that the client/server terminology applies only to a single method call. The
computer running the code in the Java programming language that calls the remote method
is the client for that call, and the computer hosting the object that processes the call is
the server for that call. It is entirely possible that the roles are reversed somewhere
down the road. The server of a previous call can itself become the client when it invokes a
remote method on an object residing on another computer.

CODE: INTERFACE FOR REMOTE OBJECT

import java.rmi.*;

interface Methodimpl extends Remote

double getSqrt(double dbl) throws RemoteException;

CODE FOR SEVER APPLICATION

import java.rmi.*;

import java.rmi.registry.*;

import java.rmi.server.*;

class RMIServer extends UnicastRemoteObject implements

Methodimpl

public RMIServer() throws RemoteException

System.out.println("The server is instantiated");


}

public double getSqrt(double dbl)

return Math.sqrt(dbl);

public static void main(String[] arguments)

try

RMIServer server = new RMIServer();

Naming.rebind("//localhost/call1", server);

catch (Exception exec)

System.out.println("Error -- " +exec.toString());

exec.printStackTrace();

CODE FOR CLIENT APPLICATION

import java.rmi.*;

import java.rmi.registry.*;

class RMIClient

public static void main(String[] arguments)

try

Methodimpl mthdIp =
(Methodimpl)Naming.lookup("//localhost/call1");

double dbl = mthdIp.getSqrt(100);

System.out.println("SQRT:" + dbl);

catch (Exception exce)

System.out.println("Error -- " + exce.toString());

exce.printStackTrace();

Output:
Practical no:-2

Aim:

a. Program to display Summation of numbers using thread

Description: Thread often called light-weight process because


operating system generally requires fewer resources to create or
manage threads than to create manage processes. python programs can
define threads by inheriting from class threading. Thread and
overriding its functionality.

Code:

import threading
import logging
def summation(number,name):
logging.info (f'Thread{name} : starting')
sum=0
for i in range(1,number+1):
sum+=i
print(f'sum of {number} is {sum}')
logging.info(f'Thread{name} : stopping')
format="%(asctime)s:%(message)s"
logging.basicConfig(format=format,level=logging.INFO,datefmt="%H:
%M: %S")
logging.info("main: before creating thread")
x=threading.Thread(target= summation, args=(30,1))
logging.info("main: before running thread")
x.start()
logging.info("main: waiting for the thread to finish")
x.join()
logging.info("main: all done")
Output:
Practical:2

Aim:

b. Program to display the prime numbers using thread

Code:

import threading
import logging
def prime(n,name):
logging.info(f' Thread{name} started')
print(f'The prime numbers are upto {n} are')
for i in range(1,n):
if i>1:
for j in range(2,i):
if(i % j==0):
break
else:
print(i)
logging.info(f'Thread{name} stopping')
format=("%(asctime)s:%(message)s")
logging.basicConfig(format=format,level=logging.INFO,datefm
t="%H:%M:%S")
logging.info("Main: before creating thread")
x=threading.Thread(target=prime,args=(25,1))
logging.info("Main: before starting thread")
x.start()
logging.info("Main: waiting thread to finish")
x.join()
logging.info("Main: All done")

Output:
Practical no: 2

Aim:

c. Program to display the Fibonacci series using thread

Code:

import threading
import logging
def febonacci(num,name):
logging.info(f'the thread{name} has started')
i=3
a=0
b=1
print(f'The {num} Fibonacci series generated are')
print(a)
print(b)
for i in range(i,num+1):
c=b
b=a+b
a=c
print(b)
logging.info(f'the thread{name} has stopped')
format="%(asctime)s:%(message)s"
logging.basicConfig(format=format,level=logging.INFO,datefmt="%H:%M:%S")
logging.info("Main: before creating thread ")
feb=threading.Thread(target=febonacci,args=(7,1))
logging.info("Main : before running the thread")
feb.start()
logging.info("main: waiting for the thread to finish")
feb.join()
logging.info("main: all done")
Output:
Practical No: 3

Aim: Program to implement a counted buffer Producer-Consumer


problem without Semaphore.

Code:

import threading

import time

N=4

buf=[None]*N

item=0

counter=0

def produce():

global item

item+=1

print(f"{item}Produced!\n")

return item

def producer():

front=0

global counter

while counter <= N:

x=produce()
counter+=1

buf[front]=x

front=(front+1)%N

time.sleep(2)

def consume(y):

print(f"{item}consumed\n")

def consumer():

rear=0

global counter

while counter!=0:

y=buf[rear]

counter-=1

consume(y)

rear=(rear+1)%N

time.sleep(5)

producer_thread=threading.Thread(target=producer)

consumer_thread=threading.Thread(target=consumer)

consumer_thread.start()

producer_thread.start()
Output:
Aim: program to implement a counted buffer Produced-
Consumer problem with Semaphore.
Code:
import threading
import time
N=4
buf=[None]*N
item=0
fill_count=threading.Semaphore(0)
empty_count=threading.Semaphore(N)
def produce():
global item
item+=1
print(f"{item}Produced!\n")
return item
def producer():
front=0
while True:
x=produce()
empty_count.acquire()
buf[front]=x
fill_count.release()
front=(front+1)%N
time.sleep(2)
def consume(y):
print(f"{item}consumed\n")
def consumer():
rear=0
while True:
fill_count.acquire()
y=buf[rear]
empty_count.release()
consume(y)
rear=(rear+1)%N
time.sleep(10)
producer_thread=threading.Thread(target=producer)
consumer_thread=threading.Thread(target=consumer)
consumer_thread.start()
producer_thread.start()

0utput:
Practical No: 4

Aim : Program to simulate FCFS algorithm and calculate average waiting


and average turnaround time. 
 
def getwaitingtime(n,bt,at,wt): 
    st=[0]*n               
    for i in range(1,n): 
        st[i]=st[i-1]+bt[i-1] 
        wt[i]=st[i]-at[i] 
 
def gettat(n,bt,wt,tat):    
    for i in range(n): 
        tat[i]=wt[i]+bt[i] 
         
def getaverage(n,p,bt,at): 
    wt=[0]*n 
    tat=[0]*n 
    getwaitingtime(n,bt,at,wt) 
    gettat(n,bt,wt,tat) 
    totwt=0                
    tottat=0               
    print("Processes\tBT\tAT\tWt\tTAT") 
    for i in range(n): 
        totwt+=wt[i] 
        tottat+=tat[i] 
        print("\tP",p[i],"\t",bt[i],"\t",at[i],"\t",wt[i],"\t",tat[i]) 
    avgwt=totwt/n 
    avgtat=tottat/n 
    print("Average Waiting time is ",round(avgwt,2)) 
    print("Average Turnaround time is ",round(avgtat,2)) 
               
         
n=int(input("Enter the Number of processes: ")) 

processes=list(map(int,input("Enter processes separated by


space").split())) 

bursttime=list(map(int,input("Enter Burst time for processes


separated by space").split())) 

arrivaltime=list(map(int,input("Enter Arrival time for processes


separated by space").split()))  
              
getaverage(n,processes,bursttime,arrivaltime) 

Output:
Practical No:5

Aim: Write a program to simulate SJF algorithm (Non pre-


emptive) and calculate average waiting time and average
turnaround time

Code:
finallist=[]

def getwt(n,plist):

runtime=[0]*n

for i in range(1,n):

finallist.append(plist[0])

prevbt=plist[0][2]

plist.pop(0)

runtime[i]=runtime[i-1]+prevbt

plist=sorted(plist,key=lambda x:(x[2],x[1]))

if runtime[i]<plist[0][1]:

plist=sorted(plist,key=lambda x:(x[1],x[2]))

plist[0][3]=runtime[i]-plist[0][1]

if plist[0][3]<0:

plist[0][3]=0

finallist.append(plist[0])

def gettat(n,plist):
for i in range(n):

plist[i][4]=plist[i][3]+plist[i][2]

def getaveragetime(n,plist):

getwt(n,plist)

plist=finallist

gettat(n,plist)

print("Process BT AT WT TAT \n")

total_wt=0

total_tat=0

for i in range(n):

total_wt+=plist[i][3]

total_tat+=plist[i][4]

print(f"P{plist[i][0]}\t{plist[i][2]}\t{plist[i][1]}\t{plist[i]
[3]}\t{plist[i][4]}")

avgwt=total_wt/n

avgtat=total_tat/n

print(f"Average waiting Time:{round(avgwt,2)}")

print(f"Average turnaround Time:{avgtat}")

process_list=[]

n=int(input("Enter number of processes"))

for i in range(n):
process=list(map(int,input(f"Enter process no Arrival time and Burst
time separated by space").split(' ')))

process.extend([0,0])

process_list.append(process)

process_list=sorted(process_list,key=lambda x:(x[1],x[2]))

print(process_list)

getaveragetime(n,process_list)

Output:
Practical No: 6

Aim: Write a program to solve readers-writers problem


Code:
import threading
import time
class ReaderWriter():
def __init__(self):
self.rd=threading.Semaphore()
self.rw=threading.Semaphore()
self.readcount=0
def reader(self):
while True:
self.rd.acquire()
self.readcount+=1
if self.readcount==1:
self.rw.acquire()
self.rd.release()
print(f"Reader {self.readcount} is reading\n")
self.rd.acquire()
self.readcount-=1
if self.readcount==0:
self.rw.release()
self.rd.release()
time.sleep(3)
def writer(self):
while True:
self.rw.acquire()
print("Writing Data------------")
self.rw.release()
time.sleep(3)
def main(self):
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()
t5=threading.Thread(target=self.writer)
t5.start()
t6=threading.Thread(target=self.reader)
t6.start()
c=ReaderWriter()
c.main()

Output:
Practical No: 7
Aim: Write a Python program that implements the banker’s
algorithm.

Code:

n=int(input("Enter the number of processes "))

m=int(input("Enter the number of resources:"))

Allocation=[]

Max=[]

Need=[]

print("Enter the Allocation Matrix: ")

for i in range(n):

theinputs=[]

for j in range(m):

x=int(input())

theinputs.append(x)

Allocation.append(theinputs)

print("Enter the Max Matrix: ")

for i in range(n):

theinputs=[]

for j in range(m):
x=int(input())

theinputs.append(x)

Max.append(theinputs)

for i in range(n):

theinputs=[]

for j in range(3):

x=Max[i][j]-Allocation[i][j]

theinputs.append(x)

Need.append(theinputs)

print(Need)

Resources=[]

print("Enter the Total Resources: ")

for i in range(m):

x=int(input())

Resources.append(x)

print(Resources)

Available=[]

for j in range(m):

x=0
for i in range(n):

x+=Allocation[i][j]

x=Resources[j]-x

Available.append(x)

print(Available)

Work=Available.copy()

Finish=[0]*n

Sequence=[]

alldone=False

attempt=0

while alldone==False:

attempt+=1

for i in range(n):

if(Finish[i]==0) and (Need[i]<=Work):

for k in range(m):

Work[k]+=Allocation[i][k]

Finish[i]=1

Sequence.append(i)

for i in range(n):

if(Finish[i]==0):
break

else:

alldone=True

if attempt>2:

break

if(alldone==True):

print("Granted!")

print("The Process Sequence:")

print(Sequence)

else:

print("Not Granted!")
Output:

You might also like