Sei sulla pagina 1di 52

CSX – 325 17103019

Experiment - 1

Aim: Introduction to shell scripting.

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 –

 Shell Keywords – if, else, break etc.


 Shell commands – cd, ls, echo, pwd, touch etc.
 Functions
 Control flow – if..then..else, case and shell loops etc.

Why do we need shell scripts


There are many reasons to write shell scripts –
 To avoid repetitive work and automation
 System admins use shell scripting for routine backups
 System monitoring
 Adding new functionality to the shell etc.

Advantages of shell scripts


 The command and syntax are exactly the same as those directly entered in command
line, so programmer do not need to switch to entirely different syntax
 Writing shell scripts are much quicker
 Quick start
 Interactive debugging etc.

Disadvantages of shell scripts


 Prone to costly errors, a single mistake can change the command which might be
harmful
 Slow execution speed
 Design flaws within the language syntax or implementation
 Not well suited for large and complex task
 Provide minimal data structure unlike other scripting languages. etc

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];
}

cout<<"Average wait time is "<<avg/n<<endl;

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];

cout<<"Enter processes ";


for(int i=0;i<n;i++)
{
cin>>process[i];
}

cout<<"Enter burst Time ";


for(int i=0;i<n;i++)
{
cin>>burstTime[i];
}

avgTime(process,burstTime,n);

return 0;
}

Output:

4
CSX – 325 17103019

Experiment - 4

Aim: To write a program for shortest job first CPU scheduling.

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};

cout<<"Enter arrival time ";


for(int i=0;i<n;i++)
{
completed[i]=false;
cin>>arrivalTime[i];
}

cout<<"Enter burst time ";


for(int i=0;i<n;i++)
{
cin>>burstTime[i];
}

int currentTime=arrivalTime[0];
queue<int>Q;
Q.push(0);

5
CSX – 325 17103019

while(!Q.empty())
{
int job=Q.front();
Q.pop();

//process the job


if(currentTime< arrivalTime[job])
{
currentTime=arrivalTime[job];
}
currentTime+=burstTime[job];
completed[job]=true;
completeTime[job]=currentTime;

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

cout<<"turn around Time ";


for(int i=0;i<n;i++)
{
cout<<turnAroundTime[i]<<" ";
}cout<<endl;

cout<<"completion Time ";


for(int i=0;i<n;i++)
{
cout<<completeTime[i]<<" ";
}cout<<endl;
return 0;
}

Output:

7
CSX – 325 17103019

Experiment - 5

Aim: To write a program for round robin CPU scheduling.

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};

cout<<"Enter arrival time ";


for(int i=0;i<n;i++)
{
completed[i]=false;
inQ[i]=false;
cin>>arrivalTime[i];
}

cout<<"Enter burst time ";


for(int i=0;i<n;i++)
{
cin>>burstTime[i];
bT[i]=burstTime[i];
}

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();

//process the job


if(burstTime[job]>tq )
{
currentTime+=tq;
burstTime[job]-=tq;
}
else
{
currentTime+=burstTime[job];
completed[job]=true;
burstTime[job]=0;
}

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);
}
}

cout<<"wait Time ";


for(int i=0;i<n;i++)
{
cout<<waitTime[i]<<" ";
}cout<<endl;

cout<<"turn around Time ";


for(int i=0;i<n;i++)
{
cout<<turnAroundTime[i]<<" ";
}cout<<endl;

cout<<"completion Time ";


for(int i=0;i<n;i++)
{

10
CSX – 325 17103019

cout<<completeTime[i]<<" ";
}cout<<endl;
return 0;
}

Output:

11
CSX – 325 17103019

Experiment - 6

Aim: To write a program for longest job first CPU scheduling.

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};

cout<<"Enter arrival time ";


for(int i=0;i<n;i++)
{
completed[i]=false;
cin>>arrivalTime[i];
}

cout<<"Enter burst time ";


for(int i=0;i<n;i++)
{
cin>>burstTime[i];
}

int currentTime=arrivalTime[0];
queue<int>Q;
Q.push(0);

12
CSX – 325 17103019

while(!Q.empty())
{
int job=Q.front();
Q.pop();

//process the job


if(currentTime< arrivalTime[job])
{
currentTime=arrivalTime[job];
}
currentTime+=burstTime[job];
completed[job]=true;
completeTime[job]=currentTime;

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

cout<<"turn around Time ";


for(int i=0;i<n;i++)
{
cout<<turnAroundTime[i]<<" ";
}cout<<endl;

cout<<"completion Time ";


for(int i=0;i<n;i++)
{
cout<<completeTime[i]<<" ";
}cout<<endl;
return 0;
}

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};

cout<<"Enter arrival time ";


for(int i=0;i<n;i++)
{
completed[i]=false;
cin>>arrivalTime[i];
}

cout<<"Enter burst time ";


for(int i=0;i<n;i++)
{
cin>>burstTime[i];
bt[i]=burstTime[i];
}

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);
}

cout<<"wait Time ";


for(int i=0;i<n;i++)
{
cout<<waitTime[i]<<" ";

16
CSX – 325 17103019

}cout<<endl;

cout<<"turn around Time ";


for(int i=0;i<n;i++)
{
cout<<turnAroundTime[i]<<" ";
}cout<<endl;

cout<<"completion Time ";


for(int i=0;i<n;i++)
{
cout<<completeTime[i]<<" ";
}cout<<endl;
return 0;
}

Output:

17
CSX – 325 17103019

Experiment - 8

Aim: To write a program for Non pre-emptive priority CPU scheduling.

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];

cout<<"Enter arrival time ";


for(int i=0;i<n;i++)
{
completed[i]=false;
cin>>arrivalTime[i];
}

cout<<"Enter burst time ";


for(int i=0;i<n;i++)
{
cin>>burstTime[i];
}

cout<<"Enter priority of processes";


for(int i=0;i<n;i++)
{
cin>>priority[i];
}

int currentTime=arrivalTime[0];

18
CSX – 325 17103019

queue<int>Q;
Q.push(0);

while(!Q.empty())
{
int job=Q.front();
Q.pop();

//process the current job


currentTime += burstTime[job];
completed[job]=true;
completeTime[job]=currentTime;
turnAroundTime[job]=completeTime[job]-arrivalTime[job];
waitTime[job]=turnAroundTime[job]-burstTime[job];

//search for new process


int mxPriority=-1;
int process=-1;

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);
}
}

cout<<"wait Time ";


for(int i=0;i<n;i++)
{
cout<<waitTime[i]<<" ";

19
CSX – 325 17103019

}cout<<endl;

cout<<"turn around Time ";


for(int i=0;i<n;i++)
{
cout<<turnAroundTime[i]<<" ";
}cout<<endl;

cout<<"completion Time ";


for(int i=0;i<n;i++)
{
cout<<completeTime[i]<<" ";
}cout<<endl;
return 0;
}

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};

cout<<"Enter arrival time ";


for(int i=0;i<n;i++)
{
completed[i]=false;
cin>>arrivalTime[i];
}

cout<<"Enter burst time ";


for(int i=0;i<n;i++)
{
cin>>burstTime[i];
bt[i]=burstTime[i];
}

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);
}

cout<<"wait Time ";


for(int i=0;i<n;i++)
{
cout<<waitTime[i]<<" ";
}cout<<endl;

22
CSX – 325 17103019

cout<<"turn around Time ";


for(int i=0;i<n;i++)
{
cout<<turnAroundTime[i]<<" ";
}cout<<endl;

cout<<"completion Time ";


for(int i=0;i<n;i++)
{
cout<<completeTime[i]<<" ";
}cout<<endl;
return 0;
}

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};

cout<<"Enter arrival time ";


for(int i=0;i<n;i++)
{
burstTime[i]=0;
wt[i]=0;

completed[i]=false;
cin>>arrivalTime[i];
}

cout<<"Enter burstTime ";


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

//check if current job was completed

if(currentTime-arrivalTime[job] == int(burstTime[job]))
{
completeTime[job]=currentTime;
turnAroundTime[job]=completeTime[job]-arrivalTime[job];
completed[job]=true;
}

//find non completed job with highest response ratio

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 not found ie no job has arrived

if(index==-1)
{
for(int i=0;i<n;i++)
{
if(completed[i]==false)
{
currentTime=arrivalTime[i];
index=i;
break;
}
}
}

//if still no job found ie all processes are completed


if(index==-1)

25
CSX – 325 17103019

{
break;
}
Q.push(index);
}

cout<<"Turn around Time is ";


for(int i=0;i<n;i++)
{
cout<<turnAroundTime[i]<<" ";
}
cout<<endl;

cout<<"Complete time is ";


for(int i=0;i<n;i++)
{
cout<<completeTime[i]<<" ";
}
cout<<endl;

cout<<"Waiting time is ";


for(int i=0;i<n;i++)
{
cout<<wt[i]<<" ";
}

return 0;
}

Output:

26
CSX – 325 17103019

Experiment - 11

Aim: To write a program for Peterson’s algorithm.

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)

{ // then producer will wait }

// otherwise producer will produce


// an item and put it into buffer (critical Section)

// Now, producer is out of critical section


flag[j] = false;
// end of code for producer

//--------------------------------------------------------
// code for consumer i

// consumer i is ready
// to consume an item
flag[i] = true;

// but producer (j) can produce an item


turn = j;

// if producer is ready to produce an item


// and if its producer's turn
while (flag[j] == true && turn == j)

{ // then consumer will wait }

// otherwise consumer will consume


// an item from buffer (critical Section)

// Now, consumer is out of critical section


flag[i] = false;
// end of code for consumer

Program:

27
CSX – 325 17103019

#include <iostream>
#include <pthread.h>

using namespace std;

pthread_mutex_t mid; //muted id


int shared=0; //global shared variable
class semaphore {
int counter;
public:
semaphore(){
}
void init(){
counter=1; //initialise counter 1 to get first thread access
}
void wait(){
pthread_mutex_lock(&mid); //lock the mutex here
while(1){
if(counter>0){ //check for counter value
counter--; //decrement counter
break; //break the loop
}

}
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() {

pthread_t id[5]; //thread ids for 5 threads


sm.init();
int i;
for(i=0;i<5;i++) //create 5 threads

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

Aim: To write a program for Bakery algorithm.

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"

// This is a memory barrier instruction.


// Causes compiler to enforce an ordering
// constraint on memory operations.
// This means that operations issued prior
// to the barrier will be performed
// before operations issued after the barrier.
#define MEMBAR __sync_synchronize()
#define THREAD_COUNT 8

volatile int tickets[THREAD_COUNT];


volatile int choosing[THREAD_COUNT];

// VOLATILE used to prevent the compiler


// from applying any optimizations.
volatile int resource;

void lock(int thread)


{

// Before getting the ticket number

30
CSX – 325 17103019

//"choosing" variable is set to be true


choosing[thread] = 1;

MEMBAR;
// Memory barrier applied

int max_ticket = 0;

// Finding Maximum ticket value among current threads


for (int i = 0; i < THREAD_COUNT; ++i) {

int ticket = tickets[i];


max_ticket = ticket > max_ticket ? ticket : max_ticket;
}

// Allotting a new ticket value as MAXIMUM + 1


tickets[thread] = max_ticket + 1;

MEMBAR;
choosing[thread] = 0;
MEMBAR;

// The ENTRY Section starts from here


for (int other = 0; other < THREAD_COUNT; ++other) {

// Applying the bakery algorithm conditions


while (choosing[other]) {
}

MEMBAR;

while (tickets[other] != 0 && (tickets[other]


< tickets[thread]
|| (tickets[other]
== tickets[thread]
&& other < thread))) {
}
}
}

// EXIT Section
void unlock(int thread)
{

MEMBAR;
tickets[thread] = 0;
}

// The CRITICAL Section


void use_resource(int thread)

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;
}

// A simplified function to show the implementation


void* thread_body(void* arg)
{
long thread = (long)arg;
lock(thread);
use_resource(thread);
unlock(thread);
return NULL;
}

int main(int argc, char** argv)


{
memset((void*)tickets, 0, sizeof(tickets));
memset((void*)choosing, 0, sizeof(choosing));
resource = 0;

// Declaring the thread variables


pthread_t threads[THREAD_COUNT];

for (int i = 0; i < THREAD_COUNT; ++i) {

// Creating a new thread with the function


//"thread_body" as its thread routine
pthread_create(&threads[i], NULL, &thread_body, (void*)((long)i));
}

for (int i = 0; i < THREAD_COUNT; ++i) {

// Reaping the resources used by


// all threads once their task is completed !
pthread_join(threads[i], NULL);
}

return 0;
}

32
CSX – 325 17103019

Experiment - 13

Aim: To write a program for Dekker’s algorithm.

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();
}

public void run()


{
while(true)
{
s.arr[id]=true;
while(s.arr[id2])
{
if(s.turn==id2)
{

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

Aim: To write a program for producer consumer problem.

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);
}
}

class Producer implements Runnable {


Q q;
Producer(Q q) {
this.q = q;
new Thread(this, "Producer").start();
}
public void run() {
int i = 0;
for(int j=0;j<10;j++) {
q.put(i++);
}
}
}

class Consumer implements Runnable {


Q q;
Consumer(Q q) {
this.q = q;
new Thread(this, "Consumer").start();
}
public void run() {
for(int j=0;j<10;j++) {
q.get();

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

Aim: To write a program for Reader-Writer problem.

import java.util.concurrent.Semaphore;

class Shared
{
public static int val=0;
}

class reader implements Runnable


{ Thread t;
Shared s;
int k=100;
boolean b=true;
Semaphore rsem, wsem;
static int readcount=0;

reader(Shared s,Semaphore rsem, Semaphore wsem)


{
this.s=s;
this.rsem=rsem;
this.wsem=wsem;
t=new Thread(this,"Reader");
t.setPriority(10);
//t.start();
}

public void run()


{
try
{
while(k>0)
{
System.out.println("Reader waiting for lock");
rsem.acquire();
System.out.println("Lock granted");
readcount++;
if(readcount==1)
wsem.acquire();
rsem.release();

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;
}
}

class writer implements Runnable


{
Thread t;
Semaphore rsem,wsem;
Shared s;
int k=100;
boolean b=true;
writer(Shared s,Semaphore rsem, Semaphore wsem)
{
this.s=s;
this.rsem=rsem;
this.wsem=wsem;
t=new Thread(this,"Writer");
t.setPriority(9);
//t.start();
}

public void run()


{
try
{
while(k>0)
{
wsem.acquire();
s.val++;
System.out.println("Writer: "+s.val);
t.sleep(1000);
wsem.release();
k--;
}
}
catch(Exception e)
{
System.out.println("Exception Caught");
}
}

38
CSX – 325 17103019

public void stopi()


{
b=false;
}
}

public class readerWriter {

public static void main(String[] args) {


Shared s=new Shared();
Semaphore rsem=new Semaphore(1);
Semaphore wsem=new Semaphore(1);
reader r=new reader(s,rsem,wsem);
writer w=new writer(s,rsem,wsem);
w.t.start();
r.t.start();

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

Aim: To write a program to implement the solution of Dining Philosophers problem.

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.

/*public class diningphilosopher {

}
*/
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);

// check for deadlock


boolean deadlock = true;
for (Fork f : forks) {
if (f.isFree()) {
deadlock = false;
break;
}
}
if (deadlock) {
Thread.sleep(1000);
System.out.println("There is a deadlock!");
break;
}
}
catch (Exception e) {
e.printStackTrace(System.out);

42
CSX – 325 17103019

}
}
System.out.println("Bye!");
System.exit(0);
}
}

43
CSX – 325 17103019

Experiment - 17

Aim: To write a program to implement solution to deadlock problem using Banker’s


algorithm.

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 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]){

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;
}
}
}
}

printf("Following is the SAFE Sequence\n");


for (i = 0; i < n - 1; i++)
printf(" P%d ->", ans[i]);
printf(" P%d", ans[n - 1]);

return (0);

Output:

45
CSX – 325 17103019

Experiment - 18

Aim: To write a program to implement FIFO page replacement algorithm.

#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

cout<<"\n The number of page faults is: "<<fault<<"\n";


}

47
CSX – 325 17103019

Experiment - 19

Aim: To write a program to implement LRU page replacement algorithm.

#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

Aim: To write a program to implement Optimal Page Replacement algorithm.

#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";

it=std::find (v.begin(), v.end(), *res);


v.erase(it);
v.push_back(a[i]);
}
}
cout<<"\n Frames :";
for(int i=0; i<v.size();++i){
cout<<v[i]<<" ";
}
cout<<"\ ****** \n";
}

cout<<"\n#####\n";
cout<<"\n Total number of page faults are: "<<fault;
}

52

Potrebbero piacerti anche