0% found this document useful (0 votes)
85 views57 pages

19BCS1762 Experiment1,2,3,4,5,6

The document is a student's practical file for their Real Time System Lab course. It contains information such as the student's name and ID, the course name and code, and an index listing 10 experiments to be completed for the course. The first experiment involves implementing various CPU scheduling algorithms like round robin, shortest job first, and priority scheduling. Pseudocode and C++ code is provided for implementing each algorithm.

Uploaded by

Vatsal Sharma
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
85 views57 pages

19BCS1762 Experiment1,2,3,4,5,6

The document is a student's practical file for their Real Time System Lab course. It contains information such as the student's name and ID, the course name and code, and an index listing 10 experiments to be completed for the course. The first experiment involves implementing various CPU scheduling algorithms like round robin, shortest job first, and priority scheduling. Pseudocode and C++ code is provided for implementing each algorithm.

Uploaded by

Vatsal Sharma
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PDF, TXT or read online on Scribd
You are on page 1/ 57

PRACTICAL FILE

Student Name Vatsal Sharma


UID 19BCS1762
Section & 19BCS-20 Group-A
Group
Department Computer Science & Engineering
Session Feb-May 2023
Course Name Real Time System Lab
Course Code CSP-457
Semester 8th
INDEX

S.NO EXPERIMENT DATE MARKS SIGNATURE

1. Write a program to implement the


following CPU scheduling. a) Round
Robin b) SJF c) FCFS d) Priority.

2. Implement producer Consumer


problem using semaphore.

3. Write a program to simulate the


following file allocation strategies. a)
Sequential b) Indexed c) Linked

4. Write a program to simulate the


concept of DiningPhilosophers problem

5. Write a program to simulate Bankers


algorithm for the purpose of deadlock
avoidance

6. Write a program to simulate disk


scheduling algorithms. a) FCFS b) SCAN

7. Write a program to simulate UNIX


commands like ls, grep, etc.

8. Write a program to simulate the MVT.

9. Write a program to simulate the MFT.

10. Write a program to simulate LRU Page


Replacement Algorithm.
Experiment:1

AIM:Write a program for implementation of CPU scheduling algorithms.


SOFTWARE REQUIRED: Turbo c++ .
DESCRIPTION:

1. FCFS CPU SCHEDULING ALGORITHM :- For FCFS scheduling algorithm, read the
number of processes/jobs in the system, their CPU burst times. The scheduling is
performed on the basis of arrival time of the processes irrespective of their other
parameters. Each process will be executed according to its arrival time. Calculate the
waiting time and turnaround time of each of the processes accordingly.
2. SJF CPU SCHEDULING ALGORITHM :- For SJF scheduling algorithm, read the number
of processes/jobs in the system, their CPU burst times. Arrange all the jobs in order
with respect to their burst times. There may be two jobs in queue with the same
execution time, and then FCFS approach is to be performed. Each process will be
executed according to the length of its burst time. Then calculate the waiting time
and turnaround time of each of the processes accordingly.
3. ROUND ROBIN CPU SCHEDULING ALGORITHM :- For round robin scheduling
algorithm, read the number of processes/jobs in the system, their CPU burst times,
and the size of the time slice. Time slices are assigned to each process in equal
portions and in circular order, handling all processes execution. This allows every
process to get an equal chance. Calculate the waiting time and turnaround time of
each of the processes accordingly.
4. PRIORITY CPU SCHEDULING ALGORITHM :- For priority scheduling algorithm, read
the number of processes/jobs in the system, their CPU burst times, and the priorities.
Arrange all the jobs in order with respect to their priorities. There may be two jobs in
queue with the same priority, and then FCFS approach is to be performed. Each
process will be executed according to its priority. Calculate the waiting time and
turnaround time of each of the processes accordingly.
PSEUDO CODE/ALGORITHMS/FLOWCHART/STEPS:
1. FCFS CPU SCHEDULING ALGORITHM:
Assigner (R(ti), RSP, MSP)
r listß RSP (R(ti))
for each r belongs to r list do
Mß MSP (r,M,e)
if M= NULL then
assign(r,M)
end if
end for
2. SJF CPU SCHEDULING ALGORITHM

Sort all the processes according to the arrival time. Then select that process that has
minimum arrival time and minimum Burst time.
After completion of the process make a pool of processes that arrives afterward till the
completion of the previous process and select that process among the pool which is having
minimum Burst time.
3. ROUND ROBIN CPU SCHEDULING ALGORITHM
Create an array rem_bt[] to keep track of remaining burst time of processes. This array is
initially a copy of bt[] (burst times array) Create another array wt[] to store waiting times of
processes. Initialize this array as 0.
Initialize time : t = 0 Keep traversing all the processes while they are not done. Do following
for i’th process if it is not done yet.
If rem_bt[i] > quantum
t = t + quantum
rem_bt[i] -= quantum;
Else // Last cycle for this process
t = t + rem_bt[i];
wt[i] = t – bt[i]

rem_bt[i] = 0; // This process is over


4. PRIORITY CPU SCHEDULING ALGORITHM
First input the processes with their arrival time, burst time and priority.
First process will schedule, which have the lowest arrival time, if two or more processes will
have lowest arrival time, then whoever has higher priority will schedule first.
Now further processes will be schedule according to the arrival time and priority of the
process.(Here we are assuming that lower the priority number having higher priority). If two
process priority are same then sort according to process number.
Note: In the question, They will clearly mention, which number will have higher priority and
which number will have lower priority.
Once all the processes have been arrived, we can schedule them based on their priority.
IMPLEMENTATION:
1. FCFS CPU SCHEDULING ALGORITHM
#include<iostream>
using namespace std;
void findWaitingTime(int processes[], int n,int bt[], int wt[])

{
wt[0] = 0;
for (int i = 1; i < n ; i++ )
wt[i] = bt[i-1] + wt[i-1] ;
}

void findTurnAroundTime( int processes[], int n,int bt[], int wt[], int tat[])
{
for (int i = 0; i < n ; i++)
tat[i] = bt[i] + wt[i];
}

void findavgTime( int processes[], int n, int bt[])


{
int wt[n], tat[n], total_wt = 0, total_tat = 0;
findWaitingTime(processes, n, bt, wt);
findTurnAroundTime(processes, n, bt, wt, tat);
cout << "Processes "<< " Burst time "<< " Waiting time " << " Turn around time\n";
for (int i=0; i<n; i++)
{
total_wt = total_wt + wt[i];
total_tat = total_tat + tat[i];
cout << " " << i+1 << "\t\t" << bt[i] <<"\t " << wt[i] <<"\t\t " << tat[i] <<endl;

}
cout << "Average waiting time = "<< (float)total_wt / (float)n;
cout << "\nAverage turn around time = "<< (float)total_tat / (float)n;
}
int main()
{
int processes[] = { 1, 2, 3};
int n = sizeof processes / sizeof processes[0];
//Burst time of all processes
int burst_time[] = {24,3,3};
findavgTime(processes, n, burst_time);
return 0;
}
2. SJF CPU SCHEDULING ALGORITHM
#include <stdio.h>
int main()
{

int A[100][4];
int i, j, n, total = 0, index, temp;
float avg_wt, avg_tat;
printf("Enter number of process:
"); scanf("%d", &n);
printf("Enter Burst Time:\n");
for (i = 0; i < n; i++) {
printf("P%d: ", i + 1);
scanf("%d", &A[i][1]);
A[i][0] = i + 1;

}
for (i = 0; i < n; i++) {
index = i;
for (j = i + 1; j < n; j++)
if (A[j][1] < A[index][1])
index = j;
temp = A[i][1];
A[i][1] = A[index][1];
A[index][1] = temp;
temp = A[i][0];
A[i][0] = A[index][0];
A[index][0] = temp;
}

A[0][2] = 0;
for (i = 1; i < n; i++) {
A[i][2] = 0;
for (j = 0; j < i; j++)
A[i][2] += A[j][1];
total += A[i][2];

}
avg_wt = (float)total / n;
total = 0;
printf("P BT WT
TAT\n"); for (i = 0; i < n;
i++) { A[i][3] = A[i][1] +
A[i][2];
total += A[i][3];

printf("P%d %d %d %d\n", A[i][0],A[i][1], A[i][2], A[i][3]);


}
avg_tat = (float)total / n;
printf("Average Waiting Time= %f", avg_wt);
printf("\nAverage Turnaround Time= %f", avg_tat);
return0;
}

3. ROUND ROBIN CPU SCHEDULING ALGORITHM


#include<iostream>
using namespace std;
void findWaitingTime(int processes[], int n,int bt[], int wt[], int quantum)

{
int rem_bt[n];
for (int i = 0 ; i < n ; i++)
rem_bt[i] = bt[i];
int t = 0; // Current time
while (1)
{

bool done = true;


for (int i = 0 ; i < n; i++)
{
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;
}

}
void findTurnAroundTime(int processes[], int n, int bt[], int wt[], int tat[])
{
for (int i = 0; i < n ; i++)
tat[i] = bt[i] + wt[i];
}
void findavgTime(int processes[], int n, int bt[],int quantum)
{
int wt[n], tat[n], total_wt = 0, total_tat = 0;
findWaitingTime(processes, n, bt, wt, quantum);
findTurnAroundTime(processes, n, bt, wt, tat);
cout << "PN\t "<< " \tBT "<< " WT " << " \tTAT\n";
for (int i=0; i<n; i++)
{

total_wt = total_wt + wt[i];


total_tat = total_tat + tat[i];
cout << " " << i+1 << "\t\t" << bt[i] <<"\t " << wt[i] <<"\t\t " << tat[i] <<endl;

}
cout << "Average waiting time = "<< (float)total_wt / (float)n;
cout << "\nAverage turn around time = "<< (float)total_tat / (float)n;
}
int main()
{
int processes[] = { 1, 2, 3};
int n = sizeof processes / sizeof processes[0];
int burst_time[] = {24, 3, 3};
int quantum = 3;
findavgTime(processes, n, burst_time, quantum);
return 0;
}

4. PRIORITY CPU SCHEDULING ALGORITHM


#include <bits/stdc++.h>
using namespace std;
#define totalprocess 5
struct process
{

int at,bt,pr,pno;
};
process proc[50];
bool comp(process a,process b)
{if(a.at == b.at)
{
return a.pr<b.pr;
}
else
{
return a.at<b.at;
}
}
void get_wt_time(int wt[])
{
int service[50];
service[0] = proc[0].at;
wt[0]=0;
for(int i=1;i<totalprocess;i++)

{
service[i]=proc[i-1].bt+service[i-1];
wt[i]=service[i]-proc[i].at;
if(wt[i]<0)
{

wt[i]=0;
}
}}
void get_tat_time(int tat[],int wt[])
{for(int i=0;i<totalprocess;i++)
{ tat[i]=proc[i].bt+wt[i];
}}
void findgc()
{int wt[50],tat[50];
double wavg=0,tavg=0;
get_wt_time(wt);
get_tat_time(tat,wt);
int stime[50],ctime[50];
stime[0] = proc[0].at;
ctime[0]=stime[0]+tat[0];
for(int i=1;i<totalprocess;i++)
{ stime[i]=ctime[i-1];
ctime[i]=stime[i]+tat[i]-wt[i]
;
}

cout<<"Process_no\tStart_time\tComplete_time\tTurn_Around_Time\tWaiting_Time"<<e
n dl;
for(int i=0;i<totalprocess;i++)
{ wavg += wt[i];
tavg += tat[i];
cout<<proc[i].pno<<"\t\t"<< stime[i]<<"\t\t"<<ctime[i]<<"\t\t"<<
tat[i]<<"\t\t\t"<<wt[i]<<endl;
}
cout<<"Average waiting time is : ";
cout<<wavg/(float)totalprocess<<endl;
cout<<"average turnaround time : ";
cout<<tavg/(float)totalprocess<<endl;
}
int main()
{int arrivaltime[] = { 1, 2, 3, 4, 5 };
int bursttime[] = { 10, 1, 2, 1, 5 };
int priority[] = { 3, 4, 1, 7, 8 };
for(int i=0;i<totalprocess;i++)
{ proc[i].at=arrivaltime[i];
proc[i].bt=bursttime[i];
proc[i].pr=priority[i];
proc[i].pno=i+1;
}

sort(proc,proc+totalprocess,comp);
findgc();
return 0;}
OUTPUT:
1. FCFS CPU SCHEDULING ALGORITHM
2. SJF CPU SCHEDULING ALGORITHM

3. ROUND ROBIN CPU SCHEDULING ALGORITHM


4. PRIORITY CPU SCHEDULING ALGORITHM
Experiment:2

AIM: Implement producer Consumer problem using semaphore.


SOFTWARE REQUIRED: Turbo c++ .
DESCRIPTION: The producer-consumer problem is an example of a multi-process
synchronization problem. The problem describes two processes, the producer and the
consumer that share a common fixed-size buffer and use it as a queue.
The producer’s job is to generate data, put it into the buffer, and start again.At the same
time, the consumer is consuming the data (i.e., removing it from the buffer), one piece at a
time.
Steps:
1. When a producer produces an item then the value of “empty” is reduced by 1
because one slot will be filled now.
2. The value of mutex is also reduced to prevent consumers from accessing the buffer.
3. Now, the producer has placed the item and thus the value of “full” is increased by 1.
4. The value of mutex is also increased by 1 because the task of producer has been
completed and consumers can access the buffer.
5. As the consumer is removing an item from the buffer, therefore the value of “full” is
reduced by 1 and the value of mutex is also reduced so that the producer cannot
access the buffer at this moment.
6. Now, the consumer has consumed the item, thus increasing the value of “empty” by
the value of mutex is also increased so that producers can access the buffer now.
IMPLEMENTATION:
#include <stdio.h>
#include <stdlib.h>
int mutex = 1,full = 0,empty = 10, x = 0;
void producer()
{

--mutex;
++full;
--empty;
x++;
printf("\nProducer produces" "item %d",x);

++mutex;
}
void consumer()
{
--mutex;
--full;
++empty;
printf("\nConsumer consumes " "item %d", x);
x--;
++mutex;
}
int main()
{
int n, i;
printf("\n1. Press 1 for Producer"
"\n2. Press 2 for Consumer"
"\n3. Press 3 for Exit");
for (i = 1; i > 0; i++) {
printf("\nEnter your choice:");
scanf("%d", &n);
switch (n) {
case 1:
if ((mutex == 1)

&& (empty != 0)) {


producer();
}

else {
printf("Buffer is full!");

}
break;
case 2:
if ((mutex == 1)
&& (full != 0)) {
consumer();
}

else { printf("Buffer is empty!");

}
break; case 3:

exit(0);
break;
}

}
}
OUTPUT:
Experiment:3

AIM: Write a program to simulate the following file allocation strategies.


1. Sequential file allocation
2. Indexed file allocation
3.Linked file allocation
SOFTWARE REQUIRED: Turbo c++ .
DESCRIPTION:
1. SEQUENTIAL FILE ALLOCATION In this file organization, the records of the file are
stored one after another both physically and logically. That is, record with sequence
number 16 is located just after the 15th record. A record of a sequential file can only
be accessed by reading all the previous records.
2. LINKED FILE ALLOCATION With linked allocation, each file is a linked list of disk blocks;
the disk blocks may be scattered anywhere on the disk. The directory contains a
pointer to the first and last blocks of the file. Each block contains a pointer to the next
block. 3.2.3
3. INDEXED FILE ALLOCATION Indexed file allocation strategy brings all the pointers
together into one location: an index block. Each file has its own index block, which is
an array of disk-block addresses. The ith entry in the index block points to the ith
block of the file. The directory contains the address of the index block. To find and
read the ith block, the pointer in the ith index-block entry is used.
PROGRAM:
1. SEQUENTIAL FILE ALLOCATION
#include<stdio.h>
#include<conio.h>
struct fileTable
{

char name[20];
int sb, nob;
}
ft[30];
void main()

{
int i, j, n; char s[20];
clrscr();
printf("Enter no of files :");
scanf("%d",&n);
for(i=0;i<n;i++)

{
printf("\nEnter file name %d :",i+1);
scanf("%s",ft[i].name);
printf("Enter starting block of file %d :",i+1);
scanf("%d",&ft[i].sb);
printf("Enter no of blocks in file %d :",i+1);
scanf("%d",&ft[i].nob);
}

printf("\nEnter the file name to be searched --


"); scanf("%s",s); for(i=0;i<n;i++)
if(strcmp(s, ft[i].name)==0)

break;
if(i==n)
printf("\nFile Not Found");
else
{

printf("\nFILE NAME START BLOCK NO OF BLOCKS BLOCKS OCCUPIED\n");


printf("\n%s\t\t%d\t\t%d\t",ft[i].name,ft[i].sb,ft[i].nob);
for(j=0;j<ft[i].nob;j++)
printf("%d, ",ft[i].sb+j);

}
getch();
}
OUTPUT:

2. LINKED FILE ALLOCATION


#include<stdio.h>
struct fileTable
{

char name[20];
int nob; struct block *sb;
}
ft[30];
struct block

{
int bno;
struct block *next;
};
void main()
{
int i, j, n;
char s[20];
struct block *temp;
printf("Enter no of files :");
scanf("%d",&n);
for(i=0;i<n;i++)
{

printf("\nEnter file name %d :",i+1);


scanf("%s",ft[i].name);
printf("Enter no of blocks in file %d :",i+1);
scanf("%d",&ft[i].nob);
ft[i].sb=(struct block*)malloc(sizeof(struct
block)); temp = ft[i].sb;
printf("Enter the blocks of the file
:"); scanf("%d",&temp->bno);
temp->next=NULL;
for(j=1;j<ft[i].nob;j++)
{

temp->next = (struct block*)malloc(sizeof(struct block));


temp = temp->next;
scanf("%d",&temp->bno);
}
temp->next = NULL;
}
printf("\nEnter the file name to be searched -- "); scanf("%s",s);
for(i=0;i<n;i++)
if(strcmp(s, ft[i].name)==0)
break;
if(i==n)

printf("\nFile Not Found");


else
{

printf("\nFILE NAME NO OF BLOCKS BLOCKS OCCUPIED");


printf("\n
%s\t\t%d\t",ft[i].name,ft[i].nob);
temp=ft[i].sb;
for(j=0;j<ft[i].nob;j++)

{
printf("%d ",temp->bno);
temp = temp->next;
}
}
}
Output:

3.INDEXED FILE ALLOCATION


#include<stdio.h>
#include<conio.h>
struct fileTable

{
char name[20];
int nob, blocks[30];
}
ft[30];
void main()
{
int i, j, n;
char s[20];
clrscr();
printf("Enter no of files :");
scanf("%d",&n);
for(i=0;i<n;i++)
{

printf("\nEnter file name %d :",i+1);


scanf("%s",ft[i].name);
printf("Enter no of blocks in file %d :",i+1);
scanf("%d",&ft[i].nob);
printf("Enter the blocks of the file
:"); for(j=0;j<ft[i].nob;j++)
scanf("%d",&ft[i].blocks[j]);
}

printf("\nEnter the file name to be searched --


"); scanf("%s",s); for(i=0;i<n;i++)
if(strcmp(s, ft[i].name)==0)
break; if(i==n)
printf("\nFile Not Found");
else
{

printf("\nFILE NAME NO OF BLOCKS BLOCKS OCCUPIED");


printf("\n
%s\t\t%d\t",ft[i].name,ft[i].nob);
for(j=0;j<ft[i].nob;j++)
printf("%d, ",ft[i].blocks[j]);

}
getch();
}
OUTPUT:
Experiment:4

AIM: To Write a C program to simulate the concept of Dining-Philosophers


problem. SOFTWARE REQUIRED: Turbo c++ .
DESCRIPTION : The dining-philosophers problem is considered a classic synchronization
problem because it is an example of a large class of concurrency-control problems. It is a
simple representation of the need to allocate several resources among several processes in
a deadlock-free and starvation-free manner. Consider five philosophers who spend their
lives thinking and eating. The philosophers share a circular table surrounded by five chairs,
each belonging to one philosopher. In the center of the table is a bowl of ri ce, and the table
is laid with five single chopsticks. When a philosopher thinks, she does not interact with her
colleagues. From time to time, a philosopher gets hungry and tries to pick up the two
chopsticks that are closest to her (the chopsticks that are between her and her left and
right neighbors). A philosopher may pick up only one chopstick at a time. Obviously, she
came to pick up a chopstick that is already in the hand of a neighbor. When a hungry
philosopher has both her chopsticks at the same time, she eats without releasing her
chopsticks. When she is finished eating, she puts down both of her chopsticks and starts
thinking again. The dining-philosophers problem may lead to a deadlock situation and
hence some rules have to be framed to avoid the occurrence of deadlock.
ALGORITHM :
void philosopher()
{
while(true)
{
THINK();
wait(S[i]
)
wait(S[(i+1)%N])
EAT();
signal(S[i])
signal(S[(i+1)%N])
THINK();
}

}
SOURCE CODE :
#include <iostream>
#include <stdlib.h>
//For exit() function
#define N 5
//No. of philosophers=5
using namespace std;
int semaphore[]={1, 1, 1, 1, 1};

//5 binary semaphores which are used as chopsticks


//wait function to decrement semaphore by 1
int wait(int x){
return (x-1);

}
//signal function to increment semaphore0 by 1
int signal_(int y){
return (y+1);

}
//Philosopher function for evaluating whether philosopher is eating or
thinking void philosopher(int i0){
wait(semaphore[i0]);
wait(semaphore[(i0+1)]%N);
cout<<"Philosopher p"<<i0<<" is eating"<<endl;
signal_(semaphore[i0]);
signal_(semaphore[(i0+1)%N]);
}

//Function overloading with increasing parameters


void philosopher(int i0, int i1)
{

if(i1==i0+2 || i1==i0+3){
cout<<"Philosopher p"<<i0<<" and p"<<i1<<" are eating"<<endl;
}
else{
cout<<"Philosopher p"<<i0<<" is eating and p"<<i1<<" is thinking"<<endl;
}
}
//3 philosophers but only 2, 1 and 0 philososphers can eat at a time
void philosopher(int i0, int i1, int i2){
if(i1==i0+2 || i1==i0+3){

cout<<"Philosopher p"<<i0<<" and p"<<i1<<" are eating and p"<<i2<<" is thinking"<<endl;


}
else if(i2==i0+2 || i2==i0+3){
cout<<"Philosopher p"<<i0<<" and p"<<i2<<" are eating and p"<<i1<<" is
thinking"<<endl;
}
else{
cout<<"Philosopher p"<<i0<<" is eating and p"<<i1<<" and p"<<i2<<" are
thinking"<<i0<<i1<<i2<<endl;
}
}
//4 philosophers
void philosopher(int i0, int i1, int i2, int i3){
if(i1==i0+2 || i1==i0+3){
cout<<"Philosopher p"<<i0<<" and p"<<i1<<" are eating and p"<<i2<<" and p"<<i3<<"
are thinking"<<endl;
}
else if(i2==i0+2 || i2==i0+3){
cout<<"Philosopher p"<<i0<<" and p"<<i2<<" are eating and p"<<i1<<" and p"<<i3<<"
are thinking"<<endl;
}
else if(i3==i0+2 || i2==i0+3){
cout<<"Philosopher p"<<i0<<" and p"<<i3<<" are eating and p"<<i1<<" and p"<<i2<<"
are thinking"<<endl;
}
}
//deadlock problem - Occurs when all the philosophers are pre-empted
//such that each philosopher takes there left chopstick simultaneously
//Solution - 4th process undergoes reversed wait working
//wait(S[(i+1)%N])
//wait(S[i])
void deadlock(){
cout<<"p0 : S0 S1\np1 : S1 S2\np2 : S2 S3\np3 : S3 S4\np4 : S4 S0"<<endl;
cout<<"p3, p2, p1, p0, p4";
}

//Driver code
int main(void)
{

int x=0;
//Selection variable for menu driven program
int i0, i1, i2, i3, i4;
//philosopher func parameters
cout<<"Enter the no. of philosophers or condition you want to execute for dining
philosophers problem:";
cout<<"\n1. 1 philosopher";
cout<<"\n2. 2 philosophers";
cout<<"\n3. 3 philosophers";
cout<<"\n4. 4 philosophers";
cout<<"\n5. Deadlock
condition";
cout<<"\n6. Exit"<<endl;

//Philosophers can only eat alternatively


//Inputs are taken sequentially like p0, p1, p3 and so
on do{
cin>>x;
switch(x){
case 1: cin>>i0;
philosopher(i0);
break;
case 2: cin>>i0>>i1;
philosopher(i0, i1);
break;
case 3: cin>>i0>>i1>>i2;
philosopher(i0, i1, i2);
break;
case 4: cin>>i0>>i1>>i2>>i3;
philosopher(i0, i1, i2, i3);
break;
case 5: deadlock();
break;
case 6: exit(0);

default: cout<<"Invalid input!";


}
}
while(1);
return 0;
}
Output:
Experiment:5

AIM: Write a program simulating bankers algorithm for the purpose of


deadlock avoidance c++.
SOFTWARE REQUIRED: Turbo c++ .
DESCRIPTION :
The banker’s algorithm is a resource allocation and deadlock avoidance algorithm that tests
for safety by simulating the allocation for predetermined maximum possible amounts of all
resources, then makes an “s-state” check to test for possible activities, before deciding
whether allocation should be allowed to continue.
Banker’s algorithm is named so because it is used in banking system to check whether loan
can be sanctioned to a person or not. Suppose there are n number of account holders in a
bank and the total sum of their money is S. If a person applies for a loan then the bank first
subtracts the loan amount from the total money that bank has and if the remaining amount
is greater than S then only the loan is sanctioned. It is done because if all the account
holders comes to withdraw their money then the bank can easily do it.
In other words, the bank would never allocate its money in such a way that it can no longer
satisfy the needs of all its customers. The bank would try to be in safe state always.
Following Data structures are used to implement the Banker’s Algorithm:
Let ‘n’ be the number of processes in the system and ‘m’ be the number of resources types.
Algorithm:
1) If Requesti <= Needi
Go to step (2) ; otherwise, raise an error condition, since the process has exceeded its
maximum claim.
2) If Requesti <= Available
Goto step (3); otherwise, Pi must wait, since the resources are not available.
3) Have the system pretend to have allocated the requested resources to process
Pi by modifying the state as
follows:
Available = Available – Requesti
Allocationi = Allocationi +
Requesti Needi = Needi– Requesti
Code:

// Banker's Algorithm
#include <iostream>
using namespace std;
int main()
{

// P0, P1, P2, P3, P4 are the Process names here


int n, m, i, j, k;
n = 5; // Number of processes
m = 3; // Number of resources
int alloc[5][3] = { { 0, 1, 0 },
// P0

// Allocation Matrix
{ 2, 0, 0 },
// P1
{ 3, 0, 2 },
// P2
{ 2, 1, 1 },
// P3
{ 0, 0, 2 } };
// P4
int max[5][3] = { { 7, 5, 3 },
// P0
// MAX Matrix
{ 3, 2, 2 },// P1
{ 9, 0, 2 }// P2
{ 2, 2, 2 }, // P3
{ 4, 3, 3 } }; // P4
int avail[3] = { 3, 3, 2 }; // Available Resources
int f[n], ans[n], ind = 0;
for (k = 0; k < n; k++) {
f[k] = 0;
}

int need[n][m];
for (i = 0; i < n; i++) {
for (j = 0; j < m; j++)
need[i][j] = max[i][j] - alloc[i][j];
}
int y = 0;
for (k = 0; k < 5; k++) {
for (i = 0; i < n; i++) {
if (f[i] == 0) {

int flag = 0;
for (j = 0; j < m; j++) {
if (need[i][j] >
avail[j]){
flag = 1;
break;
}

if (flag == 0) {
ans[ind++] = i;
for (y = 0; y < m; y++)

avail[y] += alloc[i][y];
f[i] = 1;
}
}
}
}
int flag = 1;
// To check if sequence is safe or not
for(int i = 0;i<n;i++)
{

if(f[i]==0)
{
flag = 0;
cout << "The given sequence is not safe";
break;
}

if(flag==1)
{
cout << "Following is the SAFE Sequence" << endl;
for (i = 0; i < n - 1; i++)
cout << " P" << ans[i] << " ->";
cout << " P" << ans[n - 1] <<endl;
}
return (0);
}
Output:
Experiment:6

AIM: Write a program to simulate disk scheduling algorithms. a) FCFS b) SCAN


SOFTWARE REQUIRED: Turbo c++ .
DESCRIPTION :

One of the responsibilities of the operating system is to use the hardware efficiently. For the
disk drives, meeting this responsibility entails having fast access time and large disk
bandwidth. Both the access time and the bandwidth can be improved by managing the
order in which disk I/O requests are serviced which is called as disk scheduling. The simplest
form of disk scheduling is, of course, the first-come, first-served (FCFS) algorithm. This
algorithm is intrinsically fair, but it generally does not provide the fastest service. In the
SCAN algorithm, the diskarm starts at one end, and moves towards the other end, servicing
requests as it reaches each cylinder, until it get sto the other end of the disk. At the other
end, the direction of head movement is reversed, and servicingcontinues.The head
continuously scans back and forth across the disk. C-SCAN is a variant of SCAN designed to
provide amore uniform wait time. Like SCAN, C-SCAN moves the head from one end of the
disk to the other, servicing requests along the way. When the head reaches the other end,
however, it immediately returns to the beginning of the disk without servicing any requests
on the return trip.
CODE;
#include<stdio.h>
#include<conio.h>
void main(){
int t[20], n, i, j, tohm[20], tot=0;
float avhm;clrscr();
printf("enter the no.of tracks");
scanf("%d",&n);
printf("enter the tracks to be traversed");
for(i=2;i<n+2;i++)
scanf("%d",&t[i]);
for(i=1;i<n+1;i++)
{

tohm[i]=t[i+1]-t[i];
if(tohm[i]<0) tohm[i]=tohm[i]*(-1);
}
for(i=1;i<n+1;i++)
tot+=tohm[i];
avhm=(float)tot/n;

printf("Tracks traversed \t Difference between tracks \n");


for(i=1;i<n+1;i++)
printf("%d \t \t \t %d \n",t[i],tohm[i]);

printf("\n Average header movements:%f",avhm);


getch();
}
OUTPUT:

SCAN DISK SCHEDULING ALGORITHM:


#include<stdio.h>
int main()
{

int n,r,i,j,k,p,u=0,s=0,m;
int block[10],run[10],active[10],newreq[10];
int max[10][10],resalloc[10][10],resreq[10][10];
int totalloc[10],totext[10],simalloc[10];
printf("Enter the no of processes:");
scanf("%d",&n);
printf("Enter the no ofresource
classes:"); scanf("%d",&r);
printf("Enter the total existed resource in each
class:"); for(k=1; k<=r; k++)
scanf("%d",&totext[k]);

printf("Enter the allocated


resources:"); for(i=1; i<=n; i++)
for(k=1; k<=r; k++)
scanf("%d",&resalloc[i][k]);
printf("Enter the process making the new request:");
scanf("%d",&p);
printf("Enter the requested
resource:"); for(k=1; k<=r; k++)
scanf("%d",&newreq[k]);

printf("Enter the process which are n blocked or running:");


for(i=1; i<=n; i++)
{

if(i!=p)
{
printf("process %d:\n",i+1);
scanf("%d%d",&block[i],&run[i]);
}
}
block[p]=0;
run[p]=0;
for(k=1; k<=r; k++)

j=0;
for(i=1; i<=n; i++)
{
totalloc[k]=j+resalloc[i][k];
j=totalloc[k];
}

}
for(i=1; i<=n; i++)
{
if(block[i]==1||run[i]==1)
active[i]=1;
else

active[i]=0;
}
for(k=1; k<=r; k++)
{
resalloc[p][k]+=newreq[k];
totalloc[k]+=newreq[k];
}

for(k=1; k<=r; k++)


{
if(totext[k]-totalloc[k]<0)
{
u=1;
break;
}
}
if(u==0)
{
for(k=1; k<=r; k++)
simalloc[k]=totalloc[k];
for(s=1; s<=n; s++)
for(i=1; i<=n;
i++)
{
if(active[i]==1)
{
j=0;
for(k=1; k<=r; k++)
{
if((totext[k]-simalloc[k])<(max[i][k]-resalloc[i][k]))
{
j=1;
break;
}
}
}
if(j==0)

{
active[i]=0;
for(k=1; k<=r; k++)
simalloc[k]=resalloc[i][k];

}
}
m=0;
for(k=1; k<=r; k++)
resreq[p][k]=newreq[k];
printf("Deadlock willn't occur");

}
else
{
for(k=1; k<=r; k++)
{
resalloc[p][k]=newreq[k]
; totalloc[k]=newreq[k];
}

printf("Deadlock will occur");


}
return 0;
}
OUTPUT:

You might also like

pFad - Phonifier reborn

Pfad - The Proxy pFad of © 2024 Garber Painting. All rights reserved.

Note: This service is not intended for secure transactions such as banking, social media, email, or purchasing. Use at your own risk. We assume no liability whatsoever for broken pages.


Alternative Proxies:

Alternative Proxy

pFad Proxy

pFad v3 Proxy

pFad v4 Proxy