You are on page 1of 35

1

Sonu Rajendran (Scs2122075)


OS Practical Journal
INDEX

Practical Topic Signature


No.
1 Multithreading
2 RMI
3 Producer consumer
problem (RMI)
4 FCFS algorithm
5 SJF simulation
6 Producer consumer with
semaphore
7 Bankers algorithm
2

Practical No.: 01
Aim: To implement and to explain the multithreading in Python.

Multithreading in Python

In computing, a process is an instance of a computer program that is being


executed. Any process has 3 basic components:

· An executable program.

· The associated data needed by the program (variables, work space, buffers, etc.)

· The execution context of the program (State of process)

A thread is an entity within a process that can be scheduled for execution. Also, it
is the smallest unit of processing that can be performed in an OS (Operating
System).

In simple words, a thread is a sequence of such instructions within a program that


can be executed independently of other code. For simplicity, you can assume that a
thread is simply a subset of a process!

Multiple threads can exist within one process where:

· Each thread contains its own register set and local variables (stored in stack).

· All thread of a process share global variables (stored in heap) and the program
code.
3

In a simple, single-core CPU, it is achieved using frequent switching between


threads. This is termed as context switching. In context switching, the state of a
thread is saved and state of another thread is loaded whenever any interrupt (due to
I/O or manually set) takes place. Context switching takes place so frequently that
all the threads appear to be running parallely (this is termed as multitasking).

In Python, the threading module provides a very simple and intuitive API for
spawning multiple threads in a program.

To create a new thread, we create an object of Thread class. It takes following


arguments:

· target: the function to be executed by thread

· args: the arguments to be passed to the target function

To start a thread, we use start method of Thread class.

Once the threads start, the current program (you can think of it like a main thread)
also keeps on executing. In order to stop execution of current program until a
thread is complete, we use join method.
4
5

#Program 1

Write Python Program to understand the basic working of threading module

Input:

import threading
def square(num):
print(f"Current thread is running {threading.current_thread().name}")
print(f"Square of {num} is {num*num}")
t1=threading.Thread(target=square, args=(10,), name='Thread1')
t2=threading.Thread(target=square, args=(20,), name='Thread2')
print(f"Current thread is running {threading.current_thread().name}")
t1.start()
t2.start()
t1.join()
t2.join()

Output:
6

#Program 2

Write a python multithreading program to implement a thread which accepts a


number from the user and provides the sum of the number from 1 to that number

Input:
import threading
n=int(input("Enter the number: "))
def sums():
print(f'Current Thread is {threading.current_thread().name}')
sum=0
for value in range(1,n+1):
sum=sum+value
print(f'The sum of 1 to {n} is {sum}')
t1=threading.Thread(target=sums, name='Thread1')
print(f'Current Thread is {threading.current_thread().name}')
t1.start()
t1.join()
print("Done!!")

Output:
7

#Program 3

Write a python multithreading program to accept two numbers from the user and
display all the prime numbers between the two numbers

Input:
import threading
lor=int(input("Enter the lower range: "))
upr=int(input("Enter the upper range: "))
def prime():
print(f'Current Thread is {threading.current_thread().name}')
print(f'The prime numbers between {lor} to {upr} is')
for num in range(lor,upr):
if num > 1:
for i in range(2,num):
if (num%i) == 0:
break
else:
print(num)
t1=threading.Thread(target=prime, name='Thread1')
print(f'Current Thread is {threading.current_thread().name}')
t1.start()
t1.join()
print("Done!!")
8

Output:
9

Practical No.: 02 (RMI)

1. Write a RMI program for invoking a remote method getSqrt()


that returns square root of input parameter sent by the client.
The application should consist of an Interface , Server
implementation and Client classes.

Input:
MethodImpl.java
import java.rmi.*;
interface MethodImpl extends Remote
{
double getSqrt(double db1) throws RemoteException;
}
RMIServer.java
import java,rmi.*;
import java.rmi.registry.*;
import java.rmi.server.*;
public class RMIServer extends UnicastremoteObject implements MethodImpl
{
public RMIServer() throws RemoteException
{
System.out.println("The Server is Instantiated");
}
public double getSqrt(double db1)
{
return Math.sqrt(db1);
}
public static void main(String[] arguments)
{
try
{
RMIServer server = new RMIServer();
Naming.rebind("//localhost/call1", server);
}
catch (Exception exce)
{
System.out.println("Error --" +exce.toString());
exce.printStackTrace();
}
10

}
}
RMIClient.java
import java,rmi.*;
import java.rmi.registry.*;
public class RMIClient
{
public static void main(String[] arguments)
{
try
{
MethodImpl mthdIp =
(MethodImpl)Naming.lookup("//localhost/call1");
double db1 = mthdIp.getSqrt(100);
System.out.println("SQRT is:" + db1);
}
catch (Exception exec)
{
System.out.println("Error -- " + exec.toString());
exec.printStackTrace();
}
}
}
11

Output:
12

2. Write a RMI program for invoking a remote method


primeSum() that returns sum of all prime numbers between
the two input parameters sent by the client. The application
should consist of an interface, Server Implementation and
Client classes
Input:
MethodImpl.java
import java.rmi.*;
interface MethodImpl extends Remote
{
double PrimeSum(int a,int b) throws RemoteException;
}
RMIServer.java
import java,rmi.*;
import java.rmi.registry.*;
import java.rmi.server.*;
public class RMIServer extends UnicastremoteObject implements MethodImpl
{
public RMIServer() throws RemoteException
{
System.out.println("The Server is Instantiated");
}
public double PrimeSum(int a,int b)
{
int sum=0,i,j;
for(i=a;i<=b;i++)
{
if(i==1||i==0)
{
continue;
}
int flag=1;
for(j=2;j<1/2;j++)
{
if(i%j==0)
{
flag=0;
13

break;
}
}
if(flag==1)
{
sum=sum+i;
}
}
return sum;
}
public static void main(String[] arguments)
{
try
{
RMIServer server = new RMIServer();
Naming.rebind("//localhost/call1", server);
}
catch (Exception exce)
{
System.out.println("Error --" +exce.toString());
}
}
}
RMIClient.java
import java,rmi.*;
import java.rmi.registry.*;
public class RMIClient
{
public static void main(String[] arguments)
{
try
{
MethodImpl mthdIp =
(MethodImpl)Naming.lookup("//localhost/call1");
double sum = mthdIp.PrimeSum(1,20);
System.out.println("Sum of Prime Number Between 1 to 20 is:"
+ sum);
14

}
catch (Exception exec)
{
System.out.println("Error -- " + exec.toString());
exec.printStackTrace();
}
}
}
15

Output:
16

3. Write a RMI program for invoking a remote method


factorial() that returns factorial of the input parameter sent by
the client. The application should consist of an interface,
Server Implementation and Client classes

Input:
MethodImpl.java
import java.rmi.*;
interface MethodImpl extends Remote
{
double getfact(double fact) throws RemoteException;
}
RMIServer.java
import java,rmi.*;
import java.rmi.registry.*;
public class RMIClient
{
public static void main(String[] arguments)
{
try
{
MethodImpl mthdIp =
(MethodImpl)Naming.lookup("//localhost/call1");
double fact = mthdIp.getfact(5);
System.out.println("Factorial of the number is:" + fact);
}
catch (Exception exec)
{
System.out.println("Error -- " + exec.toString());
exec.printStackTrace();
}
}
}
RMIClient.java
import java,rmi.*;
import java.rmi.registry.*;
import java.rmi.server.*;
public class RMIServer extends UnicastRemoteObject implements MethodImpl
{
public RMIServer() throws RemoteException
17

{
System.out.println("The Server is Instantiated");
}
public double getfact(double fact)
{
int i;
double f=1;
for(i=1;i<=fact;i++)
{
f=f*i;
}
return f;
}
public static void main(String[] arguments)
{
try
{
RMIServer server = new RMIServer();
Naming.rebind("//localhost/call1", server);
}
catch (Exception exce)
{
System.out.println("Error --" +exce.toString());
exce.printStackTrace();
}
}
}
18

Output:
19

Practical No.: 03

1. Write a python program to simulate Bounded buffer Producer


- Consumer problem without synchronization.

Input:

from threading import Thread

import time;

class buffer:

def __init__(self,size):

self.size=size

self.buf=[0]*size

self.into=0

self.out=0

self.counter=0

def getvalue(self):

x=self.buf[self.out]

self.out=(self.out+1)%self.size

self.counter-=1

return x

def putvalue(self,value):

self.buf[self.into]=value

self.into=(self.into+1)%self.size

self.counter+=1

class Producer(Thread):

def __init__(self,b):
20

super(Producer,self).__init__()

self.b=b

def run(self):

i=0

while self.b.counter<self.b.size:

i+=1

self.b.putvalue(i)

print(f'{i} put in Buffer\n')

print(f'Buffer Size after production:{self.b.counter}')

time.sleep(3)

class Consumer(Thread):

def __init__(self,b):

super(Consumer,self).__init__()

self.b=b

def run(self):

while self.b.counter!=0:

value=self.b.getvalue()

print(f'{value} consumed from Buffer\n')

print(f'Buffer Size after consumption:{self.b.counter}')

time.sleep(10)

b=buffer(5)

p=Producer(b)

c=Consumer(b)

p.start()
21

c.start()

c.join()

p.join()
22

Output:
23

Practical No.: 04

1. Write a python program to simulate First Come First Serve


(FCFS) Algorithm

Input:

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(f"\tP{p[i]}\t{bt[i]}\t{at[i]}\t{wt[i]}\t{tat[i]}")
24

avgwt=totwt/n

avgtat=tottat/n

print(f"Average Waiting time is {round(avgwt,2)}")

print(f"Average Turnaround time is {round(avgtat,2)}")

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

processes=list(map(int,input(f"Enter {n} process numbers seperated by space").split()))

bursttime=list(map(int,input(f"Enter Burst time for {n} processes seperated by


space").split()))

arrivaltime=list(map(int,input(f"Enter Arrival time for {n} processes seperated by


space").split()))

getaverage(n,processes,bursttime,arrivaltime)

Output:
25

Practical No.: 05

Aim: To simulate Non preemptive SJF algorithm


INPUT:
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]))
plist[0][3] =runtime[i]-plist[0][1]
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]}")
26

avgwt=total_wt/n
avgtat=total_tat/n
print(f"Average waiting Time:{round(avgwt,2)}")
print(f"Average turnaroud 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 seperated 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)
27

OUTPUT:
28

Practical No.: 06
Aim: To demonstrate Procedure consumer with semaphore
Input:
from threading import Thread
import threading
import time;
class buffer:
def __init__(self,size):
self.size=size
self.buf=[0]*size
self.into=0
self.out=0
self.empty_count = threading.Semaphore(self.size)
self.fill_count = threading.Semaphore(0)
self.mutex = threading.Semaphore(1)
def getvalue(self):
x=self.buf[self.out]
self.out=(self.out+1)%self.size
return x
def putvalue(self,value):
self.buf[self.into]=value
self.into=(self.into+1)%self.size
class Producer(Thread):
def __init__(self,b):
super(Producer,self).__init__()
self.buf=b
def run(self):
i=0
29

while True:
i+=1
self.buf.empty_count.acquire()
self.buf.mutex.acquire()
self.buf.putvalue(i)
self.buf.mutex.release()
self.buf.fill_count.release()
print(f'{i} put in Buffer \n')
time.sleep(5)
class Consumer(Thread):
def __init__(self,b):
super(Consumer,self).__init__()
self.buf=b
def run(self):
while True:
self.buf.fill_count.acquire()
self.buf.mutex.acquire()
value=self.buf.getvalue()
self.buf.mutex.release()
self.buf.empty_count.release()
print(f'{value} consumed from buffer\n')
time.sleep(5)
b=buffer(5)
p=Producer(b)
c=Consumer(b)
p.start()
c.start()
c.join()
p.join()
30

Output
:
31

Practical No.: 07
Aim: To demonstrate banker’s algorithm
Input:
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(m):
x = Max[i][j] - Allocation[i][j]
theinputs.append(x)
Need.append(theinputs)
32

print("need matrix")
print(Need)
Resources=[]
print("enter the total resources : ")
for i in range(m):
x=int(input())
Resources.append(x)
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:",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):
33

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:
34
35

S.I.E.S College of Arts, Science and Commerce


Sion(W), Mumbai – 400 022.

CERTIFICATE

This is to certify that Mr. / Miss. Sonu Rajendran Roll No. SCS2122075 Has
successfully completed the necessary course of experiments in the subject of
Operating System during the academic year 2021 – 2022 complying with the
requirements of University of Mumbai,

for the course of S.Y. BSc. Computer Science [Semester-3]

Prof. In-Charge
Ms. Maya Nair
(Operating System)

Examination Date:
Examiner’s Signature & Date:

Head of the Department


Prof. Manoj Singh
College Seal
And
Date

You might also like