Professional Documents
Culture Documents
Practical No.: 01
Aim: To implement and to explain the multithreading in Python.
Multithreading in Python
· An executable program.
· The associated data needed by the program (variables, work space, buffers, etc.)
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).
· 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 Python, the threading module provides a very simple and intuitive API for
spawning multiple threads in a program.
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
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
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
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
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
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
Input:
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)
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()
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
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
getaverage(n,processes,bursttime,arrivaltime)
Output:
25
Practical No.: 05
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
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,
Prof. In-Charge
Ms. Maya Nair
(Operating System)
Examination Date:
Examiner’s Signature & Date: