Documenti di Didattica
Documenti di Professioni
Documenti di Cultura
Experiment - 1
Theory:
Usually shells are interactive that mean, they accept command as input from users and
execute them. However, some time we want to execute a bunch of commands routinely, so
we have type in all commands each time in terminal.
As shell can also take commands as input from file we can write these commands in a file
and can execute them in shell to avoid this repetitive work. These files are called Shell
Scripts or Shell Programs. Shell scripts are similar to the batch file in MS-DOS. Each shell
script is saved with .sh file extension eg. myscript.sh
A shell script has syntax just like any other programming language. If you have any prior
experience with any programming language like Python, C/C++ etc. it would be very easy to
get started with it.
A shell script comprises following elements –
1
CSX – 325 17103019
Experiment - 2
Aim: To write a shell script to read a file. It should read a the starting and ending index and
read the file and save the output.
Program:
#!/bin/bash
echo "enter the filename"
read fname
echo "enter the starting line number"
read s
echo "enter the ending line number"
read n
sed -n $s,$n\p $fname | cat > newline
cat newline
Output:
2
CSX – 325 17103019
Experiment - 3
Aim: To write a program for first come first serve CPU scheduling.
Theory:
Simplest scheduling algorithm that schedules according to arrival times of processes. First
come first serve scheduling algorithm states that the process that requests the CPU first is
allocated the CPU first. It is implemented by using the FIFO queue. When a process enters
the ready queue, its PCB is linked onto the tail of the queue. When the CPU is free, it is
allocated to the process at the head of the queue. The running process is then removed from
the queue. FCFS is a non-preemptive scheduling algorithm.
Algorithm:
1- Input the processes along with their burst time (bt).
2- Find waiting time (wt) for all processes.
3- As first process that comes need not to wait so waiting time for process 1 will be 0 i.e.
wt[0] = 0.
4- Find waiting time for all other processes i.e. for process i ->
wt[i] = bt[i-1] + wt[i-1] .
5- Find turnaround time = waiting_time + burst_time for all processes.
6- Find average waiting time =
i. total_waiting_time / no_of_processes.
7- Similarly, find average turnaround time =
ii. total_turn_around_time / no_of_processes.
Program:
#include<iostream>
using namespace std;
void avgTime(int process[],int burstTime[],int n)
{
int waitTime[n];
int turnAroundTime[n];
double avg=0;
waitTime[0]=0;
for(int i=1;i<n;i++)
{
waitTime[i]=burstTime[i-1]+waitTime[i-1];
avg+=waitTime[i];
}
avg=0;
for(int i=0;i<n;i++)
{
turnAroundTime[i]=burstTime[i]+waitTime[i];
avg+=turnAroundTime[i];
}
cout<<"Average turn around time is "<<avg/n;
3
CSX – 325 17103019
}
int main()
{
int n;
cout<<"Enter no of processes ";
cin>>n;
int process[n];
int burstTime[n];
avgTime(process,burstTime,n);
return 0;
}
Output:
4
CSX – 325 17103019
Experiment - 4
Theory:
Process which have the shortest burst time are scheduled first. If two processes have the same
bust time then FCFS is used to break the tie. It is a non-pre-emptive scheduling algorithm.
Algorithm:
1. Sort all the process according to the arrival time.
2. Then select that process which has minimum arrival time and minimum Burst
time.
3. After completion of process make a pool of process which after till the completion
of previous process and select that process among the pool which is having
minimum Burst time.
Program:
#include<iostream>
#include<queue>
using namespace std;
int main()
{
int n;
cout<<"Enter no of processes ";
cin>>n;
bool completed[n];
int arrivalTime[n];
int burstTime[n];
int completeTime[n]={0};
int turnAroundTime[n]={0};
int waitTime[n]={0};
int currentTime=arrivalTime[0];
queue<int>Q;
Q.push(0);
5
CSX – 325 17103019
while(!Q.empty())
{
int job=Q.front();
Q.pop();
turnAroundTime[job]=completeTime[job]-arrivalTime[job];
waitTime[job]=turnAroundTime[job]-burstTime[job];
int minIndex=99999;
int minBurst=99999;
for(int i=0;i<n;i++)
{
if(completed[i]==false && currentTime>=arrivalTime[i] && minBurst>burstTime[i])
{
minIndex=i;
minBurst=burstTime[i];
}
}
if(minIndex==99999)
{
for(int i=0;i<n;i++)
{
if(!completed[i])
{
minIndex=i;
break;
}
}
}
if(minIndex==99999)
{
break;
}
Q.push(minIndex);
}
cout<<"wait Time ";
for(int i=0;i<n;i++)
{
cout<<waitTime[i]<<" ";
}cout<<endl;
6
CSX – 325 17103019
Output:
7
CSX – 325 17103019
Experiment - 5
Theory:
Each process is assigned a fixed time(Time Quantum/Time Slice) in cyclic way. It is
designed especially for the time-sharing system. The ready queue is treated as a circular
queue. The CPU scheduler goes around the ready queue, allocating the CPU to each process
for a time interval of up to 1-time quantum. To implement Round Robin scheduling, we keep
the ready queue as a FIFO queue of processes. New processes are added to the tail of the
ready queue. The CPU scheduler picks the first process from the ready queue, sets a timer to
interrupt after 1-time quantum, and dispatches the process. One of two things will then
happen. The process may have a CPU burst of less than 1-time quantum. In this case, the
process itself will release the CPU voluntarily. The scheduler will then proceed to the next
process in the ready queue. Otherwise, if the CPU burst of the currently running process is
longer than 1-time quantum, the timer will go off and will cause an interrupt to the operating
system. A context switch will be executed, and the process will be put at the tail of the ready
queue. The CPU scheduler will then select the next process in the ready queue.
Algorithm:
1- 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)
2- Create another array wt[] to store waiting times
of processes. Initialize this array as 0.
3- Initialize time : t = 0
4- Keep traversing the all processes while all processes
are not done. Do following for i'th process if it is
not done yet.
a- If rem_bt[i] > quantum
(i) t = t + quantum
(ii) bt_rem[i] -= quantum;
c- Else // Last cycle for this process
(i) t = t + bt_rem[i];
(ii) wt[i] = t - bt[i]
(ii) bt_rem[i] = 0; // This process is over
Program:
#include<iostream>
#include<queue>
using namespace std;
int main()
{
int n;
cout<<"Enter no of processes ";
cin>>n;
bool completed[n];
bool inQ[n];
int arrivalTime[n];
8
CSX – 325 17103019
int burstTime[n],bT[n];
int completeTime[n]={0};
int turnAroundTime[n]={0};
int waitTime[n]={0};
int tq=2;
int currentTime=arrivalTime[0];
queue<int>Q;
Q.push(0);
inQ[0]=true;
while(!Q.empty())
{
int job=Q.front();
Q.pop();
if(burstTime[job]==0)
{
inQ[job]=false;
completed[job]=true;
completeTime[job]=currentTime;
turnAroundTime[job]=completeTime[job]-arrivalTime[job];
waitTime[job]=turnAroundTime[job]-bT[job];
9
CSX – 325 17103019
bool check=false;
for(int i=0;i<n;i++)
{
if(inQ[i]==false && completed[i]==false && arrivalTime[i] <= currentTime)
{
check=true;
Q.push(i);
inQ[i]=true;
}
}
if(check==false)
{
for(int i=0;i<n;i++)
{
if(inQ[i]==false && completed[i]==false && arrivalTime[i] <= currentTime)
{
currentTime=arrivalTime[i];
check=true;
Q.push(i);
inQ[i]=true;
break;
}
}
}
if(burstTime[job]!=0)
{
inQ[job]=true;
Q.push(job);
}
}
10
CSX – 325 17103019
cout<<completeTime[i]<<" ";
}cout<<endl;
return 0;
}
Output:
11
CSX – 325 17103019
Experiment - 6
Theory:
It is similar to SJF scheduling algorithm. But, in this scheduling algorithm, we give priority
to the process having the longest burst time. This is non-pre-emptive in nature i.e., when any
process starts executing, can’t be interrupted before complete execution.
Algorithm:
1. Sort all the process according to the arrival time.
2. Then select that process which has maximum arrival time and minimum Burst time.
3. After completion of process make a pool of process which after till the completion of
previous process and select that process among the pool which is having maximum
Burst time.
Program:
#include<iostream>
#include<queue>
using namespace std;
int main()
{
int n;
cout<<"Enter no of processes ";
cin>>n;
bool completed[n];
int arrivalTime[n];
int burstTime[n];
int completeTime[n]={0};
int turnAroundTime[n]={0};
int waitTime[n]={0};
int currentTime=arrivalTime[0];
queue<int>Q;
Q.push(0);
12
CSX – 325 17103019
while(!Q.empty())
{
int job=Q.front();
Q.pop();
turnAroundTime[job]=completeTime[job]-arrivalTime[job];
waitTime[job]=turnAroundTime[job]-burstTime[job];
int mxIndex=-1;
int mxBurst=-1;
for(int i=0;i<n;i++)
{
if(completed[i]==false && currentTime>=arrivalTime[i] && mxBurst<burstTime[i])
{
mxIndex=i;
mxBurst=burstTime[i];
}
}
if(mxIndex==-1)
{
for(int i=0;i<n;i++)
{
if(!completed[i])
{
mxIndex=i;
break;
}
}
}
if(mxIndex==-1)
{
break;
}
Q.push(mxIndex);
}
cout<<"wait Time ";
for(int i=0;i<n;i++)
{
cout<<waitTime[i]<<" ";
}cout<<endl;
13
CSX – 325 17103019
Output:
14
CSX – 325 17103019
Experiment - 7
Aim: To write a program for longest reaming job first CPU scheduling.
Theory:
It is pre-emptive mode of LJF algorithm in which we give priority to the process having
largest burst time remaining.
Algorithm:
1. First, sort the processes in increasing order of their Arrival Time.
2. Choose the process having least arrival time but with most Burst Time. Then process
it for 1 unit. Check if any other process arrives upto that time of execution or not.
3. Repeat the above both steps until execute all the processes.
Program:
#include<iostream>
#include<queue>
using namespace std;
int main()
{
int n;
cout<<"Enter no of processes ";
cin>>n;
bool completed[n];
int arrivalTime[n];
int burstTime[n];
int bt[n];
int completeTime[n]={0};
int turnAroundTime[n]={0};
int waitTime[n]={0};
int currentTime=arrivalTime[0];
queue<int>Q;
Q.push(0);
while(true)
15
CSX – 325 17103019
{
int job=Q.front();
Q.pop();
currentTime++;
burstTime[job]--;
//process the job
if(burstTime[job]==0)
{
completed[job]=true;
completeTime[job]=currentTime;
turnAroundTime[job]=completeTime[job]-arrivalTime[job];
waitTime[job]=turnAroundTime[job]-bt[job];
}
// find the longest remaining
int mxIndex=-1,mxBurst=-1;
for(int i=0;i<n;i++)
{
if(completed[i]==false && arrivalTime[i]<=currentTime && burstTime[i]>mxBurst)
{
mxBurst=burstTime[i];
mxIndex=i;
}
}
if(mxIndex==-1)
{
for(int i=0;i<n;i++)
{
if(completed[i]==false)
{
currentTime=arrivalTime[i];
mxIndex=i;
break;
}
}
}
if(mxIndex==-1)
{
break;
}
Q.push(mxIndex);
}
16
CSX – 325 17103019
}cout<<endl;
Output:
17
CSX – 325 17103019
Experiment - 8
Theory:
In Non preemptive priority scheduling we select a process with highest priority out of all
available process.
Algorithm:
1. Select the process with highest priority out of all available processes and complete it.
2. Repeat till all the processes are completed.
Program:
#include<iostream>
#include<queue>
using namespace std;
int main()
{
int n;
cout<<"Enter no of processes ";
cin>>n;
bool completed[n];
int arrivalTime[n];
int burstTime[n];
int completeTime[n]={0};
int turnAroundTime[n]={0};
int waitTime[n]={0};
int priority[n];
int currentTime=arrivalTime[0];
18
CSX – 325 17103019
queue<int>Q;
Q.push(0);
while(!Q.empty())
{
int job=Q.front();
Q.pop();
for(int i=0;i<n;i++)
{
if(completed[i]==false && arrivalTime[i]<=currentTime && priority[i]>mxPriority)
{
process=i;
mxPriority=priority[i];
}
}
if(process==-1)
{
for(int i=0;i<n;i++)
{
if(completed[i]==false)
{
currentTime=arrivalTime[i];
process=i;
break;
}
}
}
if(process!=-1)
{
Q.push(process);
}
}
19
CSX – 325 17103019
}cout<<endl;
Output:
20
CSX – 325 17103019
Experiment - 9
Aim: To write a program for Shortest Job Remaining First CPU scheduling.
Theory:
In shortest remaining job CPU scheduling we select a job whose service time is minimum. If
while executing it we encounter a job whose service time is smaller than current executing
job we pre-empt it.
Algorithm:
1. Select the job with minimum time remaining service time and start processing it.
2. If another job arrives then stop the execution of current job and process the new
job.
3. Repeat till all jobs are completed.
Program:
#include<iostream>
#include<queue>
using namespace std;
int main()
{
int n;
cout<<"Enter no of processes ";
cin>>n;
bool completed[n];
int arrivalTime[n];
int burstTime[n];
int bt[n];
int completeTime[n]={0};
int turnAroundTime[n]={0};
int waitTime[n]={0};
int currentTime=arrivalTime[0];
queue<int>Q;
Q.push(0);
21
CSX – 325 17103019
while(true)
{
int job=Q.front();
Q.pop();
currentTime++;
burstTime[job]--;
//process the job
if(burstTime[job]==0)
{
completed[job]=true;
completeTime[job]=currentTime;
turnAroundTime[job]=completeTime[job]-arrivalTime[job];
waitTime[job]=turnAroundTime[job]-bt[job];
}
// find the longest remaining
int mnIndex=-1,mnBurst=INT_MAX;
for(int i=0;i<n;i++)
{
if(completed[i]==false && arrivalTime[i]<=currentTime && burstTime[i]<mnBurst)
{
mnBurst=burstTime[i];
mnIndex=i;
}
}
if(mnIndex==-1)
{
for(int i=0;i<n;i++)
{
if(completed[i]==false)
{
currentTime=arrivalTime[i];
mnIndex=i;
break;
}
}
}
if(mnIndex==-1)
{
break;
}
Q.push(mnIndex);
}
22
CSX – 325 17103019
Output:
23
CSX – 325 17103019
Experiment - 10
Aim: To write a program for Highest response ratio next CPU scheduling.
Program:
#include<iostream>
#include<queue>
using namespace std;
int main()
{
cout<<"Enter no. of processes ";
int n;
cin>>n;
int arrivalTime[n];
float burstTime[n];
bool completed[n];
float wt[n]={0};
int turnAroundTime[n]={0};
int completeTime[n]={0};
completed[i]=false;
cin>>arrivalTime[i];
}
queue<int>Q;
int currentTime=arrivalTime[0];
Q.push(0);
while(true)
{
int job=Q.front();
Q.pop();
currentTime++;
//increment wt of all non completed jobs by one
24
CSX – 325 17103019
for(int i=0;i<n;i++)
{
if(arrivalTime[i]<=currentTime && completed[i]==false && i!=job)
{
wt[i]=wt[i]+1;
}
}
if(currentTime-arrivalTime[job] == int(burstTime[job]))
{
completeTime[job]=currentTime;
turnAroundTime[job]=completeTime[job]-arrivalTime[job];
completed[job]=true;
}
int index=-1;
float hRatio=-1;
for(int i=0;i<n;i++)
{
if(completed[i]==false && arrivalTime[i]<= currentTime && hRatio <
((wt[i]+burstTime[i]))/(burstTime[i]))
{
index=i;
hRatio=((wt[i]+burstTime[i]))/(burstTime[i]);
}
}
if(index==-1)
{
for(int i=0;i<n;i++)
{
if(completed[i]==false)
{
currentTime=arrivalTime[i];
index=i;
break;
}
}
}
25
CSX – 325 17103019
{
break;
}
Q.push(index);
}
return 0;
}
Output:
26
CSX – 325 17103019
Experiment - 11
Theory:
It is used to solve producer consumer problem.
Pseudocode-
// code for producer (j)
// producer j is ready
// to produce an item
flag[j] = true;
// but consumer (i) can consume an item
turn = i;
// if consumer is ready to consume an item
// and if its consumer's turn
while (flag[i] == true && turn == i)
//--------------------------------------------------------
// code for consumer i
// consumer i is ready
// to consume an item
flag[i] = true;
Program:
27
CSX – 325 17103019
#include <iostream>
#include <pthread.h>
}
pthread_mutex_unlock(&mid); //unlock mutex here
}
void signal(){
pthread_mutex_lock(&mid); //lock the mutex here
counter++; //increment counter
pthread_mutex_unlock(&mid); //unlock mutex here
}
};
semaphore sm;
void* fun(void* id)
{
sm.wait(); //call semaphore wait
shared++; //increment shared variable
cout<<"Inside thread "<<shared<<endl;
sm.signal(); //call signal to semaphore
}
int main() {
28
CSX – 325 17103019
pthread_create(&id[i],NULL,fun,NULL);
for(i=0;i<5;i++)
pthread_join(id[i],NULL); //join 5 threads to complete their task
cout<<"Outside thread "<<shared<<endl;//final value of shared variable
return 0;
}
Output:
29
CSX – 325 17103019
Experiment - 12
Theory:
The Bakery algorithm is one of the simplest known solutions to the mutual exclusion
problem for the general case of N process. Bakery Algorithm is a critical section solution
for N processes. The algorithm preserves the first come first serve property.
Before entering its critical section, the process receives a number. Holder of the
smallest number enters the critical section.
If processes Pi and Pj receive the same number,
if i < j
Pi is served first;
else
Pj is served first.
The numbering scheme always generates numbers in increasing order of enumeration;
i.e., 1, 2, 3, 3, 3, 3, 4, 5, …
Program:
include<windows.h>
#include "pthread.h"
#include "stdio.h"
#include<windows.h>
// Importing POSIX Operating System API library
#include "unistd.h"
#include "string.h"
30
CSX – 325 17103019
MEMBAR;
// Memory barrier applied
int max_ticket = 0;
MEMBAR;
choosing[thread] = 0;
MEMBAR;
MEMBAR;
// EXIT Section
void unlock(int thread)
{
MEMBAR;
tickets[thread] = 0;
}
31
CSX – 325 17103019
{
if (resource != 0) {
printf("Resource was acquired by %d, but is still in-use by %d!\n",
thread, resource);
}
resource = thread;
printf("%d using resource...\n", thread);
MEMBAR;
sleep(2);
resource = 0;
}
return 0;
}
32
CSX – 325 17103019
Experiment - 13
Theory:
Dekker’s algorithm was the first provably-correct solution to the critical section problem. It
allows two threads to share a single-use resource without conflict, using only shared memory
for communication. It avoids the strict alternation of a naïve turn-taking algorithm, and was
one of the first mutual exclusion algorithms to be invented.
Program:
class shared{
int turn;
boolean arr[]=new boolean[2];
shared()
{
turn =0;
arr[0]=false;
arr[1]=false;
}
}
class myThread extends Thread{
int id,id2;
shared s;
myThread(shared x,int id)
{
s=x;
this.id=id;
if(id==1)
{
id2=0;
}
else
{
id2=1;
}
start();
}
33
CSX – 325 17103019
s.arr[id]=false;
while (s.turn==id2)
{
try{
Thread.sleep(1000);
}
catch (Exception e){
}
}
s.arr[id]=true;
}
}
//critical section
System.out.println("Critical section of "+id);
s.turn=id2;
s.arr[id]=false;
try{
Thread.sleep(1000);
}
catch (Exception e){
}
}
}
}
public class p1 {
public static void main(String[] args)
{
shared s=new shared();
myThread t1=new myThread(s,0);
myThread t2=new myThread(s,1);
}
}
Output:
34
CSX – 325 17103019
Experiment - 14
Theory:
We have a buffer of fixed size. A producer can produce an item and can place in the buffer. A
consumer can pick items and can consume them. We need to ensure that when a producer is
placing an item in the buffer, then at the same time consumer should not consume any item.
In this problem, buffer is the critical section.
Program:
import java.util.LinkedList;
import java.util.Scanner;
class Q {
int n;
synchronized int get() {
System.out.println("Got: " + n);
return n;
}
synchronized void put(int n) {
this.n = n;
System.out.println("Put: " + n);
}
}
35
CSX – 325 17103019
}
}
}
public class q6 {
public static void main(String args[]) {
Q q = new Q();
new Producer(q);
new Consumer(q);
// System.out.println("Press Control-C to stop.");
}
}
Output:
36
CSX – 325 17103019
Experiment – 15
import java.util.concurrent.Semaphore;
class Shared
{
public static int val=0;
}
rsem.acquire();
System.out.println("Reader:"+readcount+" ,Value:"+s.val);
t.sleep(1500);
readcount-=1;
if(readcount==0)
wsem.release();
rsem.release();
37
CSX – 325 17103019
k--;
}
}catch(Exception e)
{
System.out.println("Exception Caught");
}
}
public void stopi()
{
b=false;
}
}
38
CSX – 325 17103019
try
{
Thread.sleep(1);
r.stopi();
w.stopi();
r.t.join();
w.t.join();
}
catch(Exception e)
{
System.out.println("Exception caught");
}
System.out.println("Exiting Main Thread");
39
CSX – 325 17103019
40
CSX – 325 17103019
Experiment – 16
Theory: The Dining Philosopher Problem states that K philosophers seated around a circular
table with one chopstick between each pair of philosophers. There is one chopstick between
each philosopher. A philosopher may eat if he can pickup the two chopsticks adjacent to him.
One chopstick may be picked up by any one of its adjacent followers but not both.
}
*/
import java.util.concurrent.Semaphore;
import java.util.concurrent.ThreadLocalRandom;
public class diningphilosopher {
static int philosophersNumber = 5;
static Philosopher philosophers[] = new Philosopher[philosophersNumber];
static Fork forks[] = new Fork[philosophersNumber];
static class Fork {
public Semaphore mutex = new Semaphore(1);
void grab() {
try {
mutex.acquire();
}
catch (Exception e) {
e.printStackTrace(System.out);
}
}
void release() {
mutex.release();
}
boolean isFree() {
return mutex.availablePermits() > 0;
}
}
static class Philosopher extends Thread {
public int number;
public Fork leftFork;
public Fork rightFork;
Philosopher(int num, Fork left, Fork right) {
number = num;
leftFork = left;
rightFork = right;
}
public void run(){
System.out.println("Hi! I'm philosopher #" + number);
while (true) {
leftFork.grab();
System.out.println("Philosopher #" + number + " grabs left fork.");
41
CSX – 325 17103019
rightFork.grab();
System.out.println("Philosopher #" + number + " grabs right fork.");
eat();
leftFork.release();
System.out.println("Philosopher #" + number + " releases left fork.");
rightFork.release();
System.out.println("Philosopher #" + number + " releases right fork.");
}
}
void eat() {
try {
int sleepTime = ThreadLocalRandom.current().nextInt(0, 1000);
System.out.println("Philosopher #" + " eats for " + sleepTime);
Thread.sleep(sleepTime);
}
catch (Exception e) {
e.printStackTrace(System.out);
}
}
}
public static void main(String argv[]) {
System.out.println("Dining philosophers problem.");
for (int i = 0; i < philosophersNumber; i++) {
forks[i] = new Fork();
}
for (int i = 0; i < philosophersNumber; i++) {
philosophers[i] = new Philosopher(i, forks[i], forks[(i + 1) % philosophersNumber]);
philosophers[i].start();
}
while (true) {
try {
// sleep 1 sec
Thread.sleep(1000);
42
CSX – 325 17103019
}
}
System.out.println("Bye!");
System.exit(0);
}
}
43
CSX – 325 17103019
Experiment - 17
Theory:
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.
Program:
#include <stdio.h>
int main()
{
int n, m, i, j, k;
n = 5;
m = 3;
int alloc[5][3] = { { 0, 1, 0 },
{ 2, 0, 0 },
{ 3, 0, 2 },
{ 2, 1, 1 },
{ 0, 0, 2 } };
int max[5][3] = { { 7, 5, 3 },
{ 3, 2, 2 },
{ 9, 0, 2 },
{ 2, 2, 2 },
{ 4, 3, 3 } };
int avail[3] = { 3, 3, 2 };
int flag = 0;
for (j = 0; j < m; j++) {
if (need[i][j] > avail[j]){
44
CSX – 325 17103019
flag = 1;
break;
}
}
if (flag == 0) {
ans[ind++] = i;
for (y = 0; y < m; y++)
avail[y] += alloc[i][y];
f[i] = 1;
}
}
}
}
return (0);
Output:
45
CSX – 325 17103019
Experiment - 18
#include<bits/stdc++.h>
using namespace std;
main()
{
int s;
cout<<"\nEnter the size :";
cin>>s;
vector<int>v;
int n;
cout<<"\n Enter the size of reference array: ";
cin>>n;
int a[n];
cout<<"\nEnter the string";
for( int i=0; i<n;++i)
cin>>a[i];
int fault=0;
map<int,int>m;
for( int i=0; i<n;++i)
{
if(m.find(a[i])==m.end())
{
fault++;
if(v.size()<s)
{
v.push_back(a[i]);
}
else
{
m.erase(v[0]);
auto it=v.begin();
v.erase(it);
v.push_back(a[i]);
}
m[a[i]]++;
}
46
CSX – 325 17103019
47
CSX – 325 17103019
Experiment - 19
#include<bits/stdc++.h>
using namespace std;
main()
{
int s;
cout<<"\nEnter the number of frames :";
cin>>s;
vector<int>v;
int n;
cout<<"\n Enter the size of reference array: ";
cin>>n;
int a[n];
cout<<"\nEnter the string";
for( int i=0; i<n;++i)
cin>>a[i];
int fault=0;
vector<int>k;
map<int,int>m;
for(int i=0; i<n;++i)
{ cout<<a[i]<<"\n";
if(m.find(a[i])==m.end())
{ // cout<<"\n Not found ";
fault++;
m[a[i]]++;
if(v.size()<s)
{
v.push_back(a[i]);
auto it = std::find (k.begin(), k.end(), a[i]);
if(it==k.end())
{
k.insert(k.begin(),a[i]);
}
else
{
k.erase(it);
k.insert(k.begin(),a[i]);
}
}
else
{
int aa=k[k.size()-1];
// cout<<"\n Page to be replaced is: "<<aa<<"\n";
auto it=std::find (v.begin(), v.end(), aa);
48
CSX – 325 17103019
m.erase(v[it-v.begin()]);
v.erase(it);
k.erase(k.end()-1);
v.push_back(a[i]);
it = std::find (k.begin(), k.end(), a[i]);
if(it==k.end())
{
k.insert(k.begin(),a[i]);
}
else
{
k.erase(it);
k.insert(k.begin(),a[i]);
}
}
}
else
{
auto it = std::find (k.begin(), k.end(), a[i]);
if(it==k.end())
{
k.insert(k.begin(),a[i]);
}
else
{
k.erase(it);
k.insert(k.begin(),a[i]);
}
}
cout<<"\n The frames are: \n";
cout<<"\n****\n";
for( int i=0; i<v.size();++i)
{
cout<<v[i]<<" ";
}
cout<<"\n****\n";
}
49
CSX – 325 17103019
cout<<"\n############\n";
cout<<"\n The number of page faults is: "<<fault<<"\n";
}
50
CSX – 325 17103019
Experiment - 20
#include<bits/stdc++.h>
using namespace std;
main()
{
int s;
cout<<"\nEnter the number of frames :";
cin>>s;
vector<int>v;
int n;
cout<<"\n Enter the size of reference array: ";
cin>>n;
vector<int> a;
int mm;
cout<<"\nEnter the string";
for( int i=0; i<n;++i)
a.push_back(mm);
}
int fault=0;
vector<int>k;
map<int,int>m;
for( int i=0; i<n;++i)
{
if(m.find(a[i])==m.end())
{
fault++;
m[a[i]]++;
if(v.size()<s){
v.push_back(a[i]);
}
else
{
auto it=a.begin();
auto res=a.begin();
int aa=0;
for( int j=0; j<v.size();++j)
{
it=std::find (a.begin()+i-1, a.end(), v[j]);
if(it==a.end())
{ //cout<<"\n YEs\n";
res=v.begin()+j;
break;
}
else if(aa<it-a.begin())
{
51
CSX – 325 17103019
res=it;
aa=it-a.begin();
}
}
cout<<"\n Element getting Replaced is :"<<*res<<"\n";
cout<<"\n#####\n";
cout<<"\n Total number of page faults are: "<<fault;
}
52