OS File67
OS File67
OPERATING SYSTEM
CSX – 325
SESSION : 2019-2020
1
17103067 CSX-325
INDEX
S. Experiment Name Page Remark
No. No.
1. Using Linux Commands 3
2. Writing Shell Scripts 4-6
3. To implement FCFS Scheduling 7-9
4. To implement SRN Scheduling 10-14
5. To implement RR Scheduling 15-20
6. To implement LCN Scheduling 21-28
7. To implement Priority Based Non preemptive 29-31
Scheduling
8. To implement Priority Based preemptive Scheduling 32-38
9. To implement Bankers Algorithm for deadlock 39-42
prevention
10. To implement Producer Consumer Problem with 43-45
Bounded Buffer
2
17103067 CSX-325
Lab 1
Aim: Introduction to shell scripting and write a shell script which will display all the files in
the current directory which are having permission of read ,write and execute..
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 have 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 Script :
echo "List of Files which have Read, Write and Execute Permissions in Current Directory"
for file in *
do
if [ -r $file -a -w $file -a -x $file ]
then
echo $file
fi
don
3
17103067 CSX-325
Lab 2
Aim: Write a program to implement First Come First Serve (FCFS) CPU scheduling.
Theory:
First come first serve (FCFS) scheduling algorithm simply schedules the jobs according to
their arrival time. The job which comes first in the ready queue will get the CPU first. The
lesser the arrival time of the job, the sooner will the job get the CPU. FCFS scheduling may
cause the problem of starvation if the burst time of the first process is the longest among all
the jobs.
Algorithm:
Program:
#include<stdio.h>
int main(){
int bt[10]={0},at[10]={0},tat[10]={0},wt[10]={0},ct[10]={0};
int n,sum=0;
float totalTAT=0,totalWT=0;
printf("Enter number of processes ");
4
17103067 CSX-325
scanf("%d",&n);
printf("Enter arrival time and burst time for each process\n\n");
for(int i=0;i<n;i++)
{
printf("Arrival time of process[%d] ",i+1);
scanf("%d",&at[i]);
printf("Burst time of process[%d] ",i+1);
scanf("%d",&bt[i]);
printf("\n");
}
for(int j=0;j<n;j++)
{
sum+=bt[j];
ct[j]+=sum;
}
for(int k=0;k<n;k++)
{
tat[k]=ct[k]-at[k];
totalTAT+=tat[k];
}
for(int k=0;k<n;k++)
{
wt[k]=tat[k]-bt[k];
totalWT+=wt[k];
}
printf("Solution: \n\n");
printf("P#\t AT\t BT\t CT\t TAT\t WT\t\n\n");
for(int i=0;i<n;i++)
5
17103067 CSX-325
{
printf("P%d\t %d\t %d\t %d\t %d\t %d\n",i+1,at[i],bt[i],ct[i],tat[i],wt[i]);
}
printf("\n\nAverage Turnaround Time = %f\n",totalTAT/n);
printf("Average WT = %f\n\n",totalWT/n);
return 0;
}
6
17103067 CSX-325
Lab 3
Aim: Write a program for shortest job first (SJF) 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-preemptive scheduling algorithm.
Algorithm:
#include<stdio.h>
int main()
{
int bt[20],p[20],wt[20],tat[20],i,j,n,total=0,pos,temp;
float avg_wt,avg_tat;
printf("Enter number of process:");
scanf("%d",&n);
printf("\nEnter Burst Time:\n");
for(i=0;i<n;i++)
{
printf("p%d:",i+1);
scanf("%d",&bt[i]);
p[i]=i+1;
7
17103067 CSX-325
}
for(i=0;i<n;i++)
{
pos=i;
for(j=i+1;j<n;j++)
{
if(bt[j]<bt[pos])
pos=j;
}
temp=bt[i];
bt[i]=bt[pos];
bt[pos]=temp;
temp=p[i];
p[i]=p[pos];
p[pos]=temp;
}
wt[0]=0;
for(i=1;i<n;i++)
{
wt[i]=0;
for(j=0;j<i;j++)
wt[i]+=bt[j];
total+=wt[i];
}
avg_wt=(float)total/n;
total=0;
8
17103067 CSX-325
for(i=0;i<n;i++)
{
tat[i]=bt[i]+wt[i];
total+=tat[i];
printf("\np%d\t\t %d\t\t %d\t\t\t%d",p[i],bt[i],wt[i],tat[i]);
}
avg_tat=(float)total/n;
printf("\n\nAverage Waiting Time=%f",avg_wt);
printf("\nAverage Turnaround Time=%f\n",avg_tat);
}
9
17103067 CSX-325
Lab 4
Aim: Write a program for Shortest time Remaining job first CPU scheduling.
Theory:
In this scheduling algorithm, the process with the smallest amount of time remaining until
completion is selected to execute. Since the currently executing process is the one with the
shortest amount of time remaining by definition, and since that time should only reduce as
execution progresses, processes will always run until they complete or a new process is added
that requires a smaller amount of time.
Algorithm: Pre-emptive version of SJF, keep switching the job on basis of the minimum
time remaining for a job and if clash occurs then choose the job with less arrival time.
#include <bits/stdc++.h>
using namespace std;
struct srtf {
int pid;
int burst;
int arrival;
};
void findWaitingTime(srtf arr[], int n, int wt[])
{
int rt[n];
for (int i = 0; i < n; i++)
rt[i] = arr[i].burst;
10
17103067 CSX-325
if (check == false) {
t++;
continue;
}
rt[shortest]--;
minm = rt[shortest];
if (minm == 0)
minm = INT_MAX;
if (rt[shortest] == 0) {
complete++;
check = false;
finish_time = t + 1;
wt[shortest] = finish_time -
arr[shortest].burst -
arr[shortest].arrival;
if (wt[shortest] < 0)
wt[shortest] = 0;
11
17103067 CSX-325
}
t++;
}
}
void findTurnAroundTime(srtf arr[], int n,
int wt[], int tat[])
{
for (int i = 0; i < n; i++)
tat[i] = arr[i].burst + wt[i];
}
void findavgTime(srtf arr[], int n)
{
int wt[n], tat[n], total_wt = 0,
total_tat = 0;
findWaitingTime(arr, n, wt);
findTurnAroundTime(arr, n, 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 << " " << arr[i].pid << "\t\t"
<< arr[i].burst << "\t\t " << wt[i]
<< "\t\t " << tat[i] << endl;
}
cout << "\nAverage waiting time = "
<< (float)total_wt / (float)n;
12
17103067 CSX-325
13
17103067 CSX-325
14
17103067 CSX-325
Lab 5
Theory:
Each process is assigned a fixed time (Time Quantum/Time Slice) in a 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:
15
17103067 CSX-325
Program:
#include<bits/stdc++.h>
using namespace std;
int main()
{
int n;
cout<<"Enter the no of processes:- ";
cin>>n;
bool completed[n];
bool inQ[n];
int arrivalTime[n];
int burstTime[n],bT[n];
int completeTime[n]={0};
int turnAroundTime[n]={0};
int waitTime[n]={0};
16
17103067 CSX-325
17
17103067 CSX-325
{
inQ[job]=false;
completed[job]=true;
completeTime[job]=currentTime;
turnAroundTime[job]=completeTime[job]-arrivalTime[job];
waitTime[job]=turnAroundTime[job]-bT[job];
}
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;
}
18
17103067 CSX-325
}
}if(burstTime[job]!=0)
{
inQ[job]=true;
Q.push(job);
}
}
19
17103067 CSX-325
20
17103067 CSX-325
LAB 6
AIM: To implement LCN Scheduling
#include<iostream>
using namespace std;
class process { public: char pid; int arr_time, burst_time, end_time, completed; void
get_data(char c, int a, int s)
{
pid=c;
arr_time=a;
burst_time=s;
completed=0;
}
};
struct node
{
process *p;
node* next;
};
class Queue
{
node *q_first, *first;
public:
Queue()
{
first=0;
q_first=0;
} void show()
{
21
17103067 CSX-325
cout<<"Queue: ";
node* t_node;
t_node=first;
while(t_node)
{
cout<<t_node->p->pid<<", ";
t_node=t_node->next;
}
cout<<"\tReady: ";
t_node=q_first;
while(t_node)
{
cout<<"("<<t_node->p->pid<<","<<t_node->p->completed<<"), ";
t_node=t_node->next;
}
cout<<endl;
} void new_process(process *pr)
{
node *p_node, *t_node, *prev;
p_node=new node;
p_node->p=pr;
p_node->next=0;
t_node=first;
if(t_node==0)
{
first=p_node;
return;
}
prev=0;
22
17103067 CSX-325
while(t_node)
{
if(t_node->p->arr_time <= p_node->p->arr_time)
{
prev=t_node;
t_node=t_node->next;
}
else
{
if(prev==0)
{
first=p_node;
p_node->next=t_node;
return;
}
prev->next=p_node;
p_node->next=t_node;
return;
}
}
prev->next=p_node;
} void LCN()
{
node *t_node, *p_node;
int time=0;
while(first!=0 || q_first!=0)
{
t_node=first;
if(t_node && t_node->p->arr_time==time)
23
17103067 CSX-325
{
p_node=t_node;
while(t_node->next && t_node->next->p->arr_time==time) t_node=t_node->next;
first=t_node->next;
t_node->next=q_first;
q_first=p_node;
}
if(q_first)
{
++time;
t_node=q_first;
++t_node->p->completed;
if(t_node->p->burst_time==t_node->p->completed)
{
t_node->p->end_time=time;
q_first=q_first->next;
}
else
{
t_node=t_node->next;
p_node=0;
while(t_node)
{
if(q_first->p->completed<t_node->p->completed)
{
if(p_node)
{
p_node->next=q_first;
q_first=q_first->next;
24
17103067 CSX-325
p_node->next->next=t_node;
break;
}
break;
}
else if(q_first->p->completed==t_node->p->completed)
{
if(q_first->p->arr_time<=t_node->p->arr_time)
{
if(p_node)
{
p_node->next=q_first;
q_first=q_first->next;
p_node->next->next=t_node;
break;
}
break;
}
else
{
p_node=t_node;
t_node=t_node->next;
}
}
else
{
p_node=t_node;
t_node=t_node->next;
}
25
17103067 CSX-325
}
if(t_node==0 && p_node!=0)
{
p_node->next=q_first;
q_first=q_first->next;
p_node->next->next=0;
}
}
}
}
}
};
int main()
{
int tot_procs, test_cases, curr_test, i, a, b, turn_ar_time, wait_time;
float avg_wait_time, avg_turn_ar_time;
char ch;
cout<<"Enter Number of Test Cases: ";
cin>>test_cases;
cout<<endl;
for(curr_test=1; curr_test<=test_cases; ++curr_test)
{
cout<<"TEST CASE "<<curr_test<<"\n\n";
cout<<"Enter Total Number of Process: ";
cin>>tot_procs;
process *pr;
pr=new process[tot_procs];
cout<<"\nEnter Data for each Process-\n\n";
for(i=0; i<tot_procs; ++i)
26
17103067 CSX-325
{
cout<<"Enter Process Name: ";
cin>>ch;
cout<<"Enter Arrival Time: ";
cin>>a;
cout<<"Enter Burst Time: ";
cin>>b;
pr[i].get_data(ch, a, b);
}
Queue q;
// cout<<"\n-------------------------INFORMATION ENTERED-------------------------
27
17103067 CSX-325
28
17103067 CSX-325
LAB 7
AIM: To implement Priority Based Non preemptive Scheduling.
#include <bits/stdc++.h>
using namespace std;
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 n)
{
int service[50];
service[0]=0;
wt[0]=0;
for(int i=1; i<n; i++)
{
service[i]=proc[i-1].bt+service[i-1];
wt[i]=service[i]-proc[i].at+1;
if(wt[i]<0) wt[i]=0;
}
}
void get_tat_time(int tat[],int wt[],int n)
{
for(int i=0; i<n; i++)
{
tat[i]=proc[i].bt+wt[i];
29
17103067 CSX-325
}
}
void findgc(int n)
{
int wt[50],tat[50];
double wavg=0,tavg=0;
get_wt_time(wt,n);
get_tat_time(tat,wt,n);
int stime[50],ctime[50];
stime[0]=1;
ctime[0]=stime[0]+tat[0];
for(int i=1; i<n; 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"<<en
dl;
for(int i=0; i<n; 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 : "<<wavg/(float)n<<endl;
cout<<"average turnaround time : ";
cout<<tavg/(float)n<<endl;
}
int main()
30
17103067 CSX-325
{
int n;
cout<<"enter number of processes : ";
cin>>n;
31
17103067 CSX-325
LAB 8
AIM: To implement Priority Based preemptive Scheduling
#include <bits/stdc++.h>
using namespace std;
struct Process
{
int processID;
int burstTime;
int tempburstTime;
int responsetime;
int arrivalTime;
int priority;
int outtime;
int intime;
};
void insert(Process Heap[], Process value, int* heapsize,
int* currentTime)
{
int start = *heapsize, i;
Heap[*heapsize] = value;
if (Heap[*heapsize].intime == -1)
Heap[*heapsize].intime = *currentTime;
++(*heapsize);
while (start != 0 && Heap[(start - 1) / 2].priority >
Heap[start].priority)
{
32
17103067 CSX-325
33
17103067 CSX-325
34
17103067 CSX-325
do
{
if (insertedprocess != n)
{
for (i = 0; i < n; i++)
{
if (array[i].arrivalTime == currentTime)
{
++insertedprocess;
35
17103067 CSX-325
array[i].intime = -1;
array[i].responsetime = -1;
insert(Heap, array[i], &heapsize,¤tTime);
}
}
}
scheduling(Heap, array, n, &heapsize, ¤tTime);
++currentTime;
if (heapsize == 0 && insertedprocess == n)
break;
}
while (1);
array[i].tempburstTime);
totalbursttime += array[i].burstTime;
}
printf("Average waiting time = %f\n", ((float)totalwaitingtime / (float)n));
printf("Average response time =%f\n", ((float)totalresponsetime / (float)n));
printf("Average turn around time = %f\n",
((float)(totalwaitingtime + totalbursttime) / (float)n));
}
int main()
{
int n,i;
36
17103067 CSX-325
37
17103067 CSX-325
38
17103067 CSX-325
LAB 9
AIM: To implement Bankers Algorithm for deadlock prevention.
#include <iostream>
using namespace std;
int main()
{
int n, m, i, j, k,index=0,flag=0,y=0;
cout<<"No. of Processes : ";
cin>>n;
cout<<"No. of resources : ";
cin>>m;
int allocation[n][m],maximum[n][m];
int available[m];
cout<<"Enter available resource : \n";
39
17103067 CSX-325
int flag = 0;
for (j = 0; j < m; j++)
{
if (need[i][j] > available[j])
{
flag = 1;
break;
}
}
40
17103067 CSX-325
if (flag == 0)
{
ans[ind++] = i;
for (y = 0; y < m; y++) available[y] +=
allocation[i][y];
f[i] = 1;
}
}
}
}
cout<<"\n\n";
for (i = 0; i < n - 1; i++)
cout<<"P"<<ans[i]<<" ";
cout<<"P" <<ans[n - 1];
return (0);
}
41
17103067 CSX-325
42
17103067 CSX-325
LAB 10
AIM: To implement Producer Consumer Problem with Bounded Buffer.
#include<stdio.h>
#include<stdlib.h>
int mutex=1,full=0,empty=3,x=0;
int main()
{
int n;
void producer();
void consumer();
int wait(int);
int signal(int);
printf("\n1.Producer\n2.Consumer\n3.Exit");
while(1)
{
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:
43
17103067 CSX-325
if((mutex==1)&&(full!=0))
consumer();
else
printf("Buffer is empty!!");
break;
case 3:
exit(0);
break;
}
}
return 0;
}
int wait(int s)
{
return (--s);
}
int signal(int s)
{
return(++s);
}
void producer()
{
mutex=wait(mutex);
full=signal(full);
empty=wait(empty);
x++;
44
17103067 CSX-325
void consumer()
{
mutex=wait(mutex);
full=wait(full);
empty=signal(empty);
printf("\nConsumer consumes item %d",x);
x--;
mutex=signal(mutex);
}
45
17103067 CSX-325
LAB 11
AIM: To implement Producer Consumer Problem with Unbounded Buffer.
#include <pthread.h>
#include <stdlib.h>
#include <unistd.h>
#include <stdio.h>
pthread_mutex_lock(&mutex);
printf("Before producer production: %d\n", buf_items);
++buf_items;
printf("After producer production: %d\n", buf_items);
pthread_cond_signal(&non_zero_item);
pthread_mutex_unlock(&mutex);
}
return NULL;
}
void* consumer(void* arg)
{
46
17103067 CSX-325
while(1)
{
usleep(CONS_DELAY);
#ifdef BAD_DESIGN
#endif
pthread_mutex_lock(&mutex); while(buf_items == 0)
pthread_cond_wait(&non_zero_item, &mutex);
printf("Before consumer consumption: %d\n",buf_items);
--buf_items;
printf("After consumer consumption: %d\n", buf_items);
pthread_mutex_unlock(&mutex);
}
return NULL;
}
return 0;
}
47
17103067 CSX-325
48
17103067 CSX-325
LAB 12
AIM: To implement Reader Writer Problem.
#include "iostream"
#include <pthread.h>
#include <unistd.h>
using namespace std;
class monitor
{
private:
int readers;
int writers;
int wait_read;
int wait_write;
pthread_cond_t can_read;
pthread_cond_t canwrite;
pthread_mutex_t condlock;
public:
monitor() ///constructor
{
readers = 0;
writers = 0;
wait_read = 0;
wait_write = 0;
pthread_cond_init(&can_read, NULL);
pthread_cond_init(&canwrite, NULL);
pthread_mutex_init(&condlock, NULL);
}
49
17103067 CSX-325
void beginread(int i)
{
pthread_mutex_lock(&condlock);
if (writers == 1 || wait_write > 0)
{
wait_read++;
pthread_cond_wait(&can_read, &condlock);
wait_read--;
}
readers++;
cout << "reader " << i << " is reading\n";
pthread_mutex_unlock(&condlock);
pthread_cond_broadcast(&can_read);
}
void endread(int i)
{
pthread_mutex_lock(&condlock);
if (--readers == 0)
pthread_cond_signal(&canwrite);
pthread_mutex_unlock(&condlock);
}
void beginwrite(int i)
{
pthread_mutex_lock(&condlock);
if (writers == 1 || readers > 0)
{
++wait_write;
50
17103067 CSX-325
pthread_cond_wait(&canwrite, &condlock);
--wait_write;
}
writers = 1;
cout << "writer " << i << " is writing\n";
pthread_mutex_unlock(&condlock);
}
void endwrite(int i)
{
pthread_mutex_lock(&condlock);
writers = 0;
if (wait_read > 0) pthread_cond_signal(&can_read);
else
pthread_cond_signal(&canwrite);
pthread_mutex_unlock(&condlock);
}
} M;
51
17103067 CSX-325
int main()
{
pthread_t r[3], w[3];
int id[3];
for (int i = 0; i < 3; i++)
{
id[i] = i;
pthread_create(&r[i], NULL, &reader, &id[i]);
pthread_create(&w[i], NULL, &writer, &id[i]);
}
52
17103067 CSX-325
}
}
53
17103067 CSX-325
LAB 13
AIM: To implement Dining Philosopher Problem.
#include<iostream>
#define n 2
using namespace std; int cPhil = 0,i; struct fork{ int taken; }ForkAvil[n]; struct ph{
int left;
int right;
} phs[n];
if(otherFork== -1)
otherFork=(n-1);
ForkAvil[philID].taken = ForkAvil[otherFork].taken = 0;
cout<<"Philosopher "<<philID+1<<" released fork "<<philID+1<<" and
fork"<<otherFork+1<<"\n";
cPhil++;
}
54
17103067 CSX-325
if(philID==(n-1))
{
if(ForkAvil[philID].taken==0)
{
ForkAvil[philID].taken = phs[philID].right = 1;
cout<<"Fork "<<philID+1<<" taken by philosopher "<<philID+1<<"\n";
}
else
{
cout<<"Philosopher "<<philID+1<<" is waiting for fork "<<philID+1<<"\n";
}
}
else
{
int dupphilID = philID;
philID-=1;
if(philID== -1)
philID=(n-1);
if(ForkAvil[philID].taken == 0)
{
ForkAvil[philID].taken = phs[dupphilID].right = 1;
cout<<"Fork "<<philID+1<<" taken by Philosopher "<<dupphilID+1<<"\n";
}
else
{
cout<<"Philosopher "<<dupphilID+1<<" is waiting for Fork"<<philID+1<<"\n";
}
}
}
else if(phs[philID].left==0)
{
55
17103067 CSX-325
if(philID==(n-1))
{
if(ForkAvil[philID-1].taken==0)
{
ForkAvil[philID-1].taken = phs[philID].left = 1;
cout<<"Fork "<<philID<<" taken by philosopher "<<philID+1<<"\n";
}
else
{
cout<<"Philosopher "<<philID+1<<" is waiting for fork "<<philID<<"\n";
}
}
else
{
if(ForkAvil[philID].taken == 0)
{
ForkAvil[philID].taken = phs[philID].left = 1;
cout<<"Fork "<<philID+1<<" taken by Philosopher "<<philID+1<<"\n";
}
else
{
cout<<"Philosopher "<<philID+1<<" is waiting for Fork"<<philID+1<<"\n";
}
}
}
}
int main()
{
for(i=0; i<n; i++)
ForkAvil[i].taken=phs[i].left=phs[i].right=0;
while(cPhil<n)
{
56
17103067 CSX-325
return 0;
57
17103067 CSX-325
LAB 14
AIM: To implement Reader Writer Problem using Semaphores.
58
17103067 CSX-325
59
17103067 CSX-325
60
17103067 CSX-325
LAB 15
AIM: To implement Dining Philosopher Problem using Semaphores.
#include <pthread.h>
#include <semaphore.h>
#include <stdio.h>
#include <windows.h>
#include <unistd.h>
#define N 5
#define THINKING 2
#define HUNGRY 1
#define EATING 0
#define LEFT (phnum + 4) % N
#define RIGHT (phnum + 1) % N
int state[N];
int phil[N] = { 0, 1, 2, 3, 4 };
sem_t mutex;
sem_t S[N];
void test(int phnum)
{
if (state[phnum] == HUNGRY
&& state[LEFT] != EATING && state[RIGHT] != EATING)
{
state[phnum] = EATING;
usleep(2);
61
17103067 CSX-325
62
17103067 CSX-325
while (1)
{
int* i = (int *)num;
usleep(1);
take_fork(*i);
usleep(0);
put_fork(*i);
}
}
int main()
{
int i;
pthread_t thread_id[N];
sem_init(&mutex, 0, 1);
for (i = 0; i < N; i++) sem_init(&S[i], 0, 0);
for (i = 0; i < N; i++)
{
pthread_create(&thread_id[i], NULL,
philospher, &phil[i]);
printf("Philosopher %d is thinking\n", i + 1);
}
for (i = 0; i < N; i++) pthread_join(thread_id[i], NULL);
}
63
17103067 CSX-325
64
17103067 CSX-325
LAB-16
AIM: To implement Dekker’s algorithm.
class basic11
{ int t=0;
boolean k=false,p1=true,p2=true; boolean p1using=false, p2using=false; public
synchronized void critical(int i)
{ t++;
System.out.println("Inside critical section "+i+" : "+t);
System.out.println("Exiting the section "+i);
}
}
class process11 implements Runnable
{
basic11 b; Thread t; process11(basic11 b)
{
this.b=b; t=new Thread(this,"Process1"); System.out.println("Process 1
Created");
t.setPriority(9);
t.start();
}
public void run() { System.out.println("RUN 1"); while(b.p1)
{
b.p1using=true; while(b.p2using)
{}
b.critical(1);
b.p1using=false;
System.out.println("Process 1 in the normal section");
if(!b.p1)
{ System.out.println("Stop1");
break;
}
}
}
public void stopi()
{System.out.println("Stop Process 1");
b.p1=false;
}
}
class process22 implements Runnable
{
basic11 b; Thread t; process22(basic11 b)
{
this.b=b; t=new Thread(this, "Process2"); System.out.println("Process 2
created ");
65
17103067 CSX-325
t.setPriority(10);
t.start();
}
public void run() { System.out.println("RUN 2"); while(b.p2)
{
b.p2using=true; while(b.p1using)
{
}
b.critical(2);
b.p2using=false;
System.out.println("Process 2 in the normal section");
if(!b.p2)
{
System.out.println("Stop2");
break;
}
}
}
public void stopi()
{ System.out.println("Stop Process 2");
b.p2=false;
}
}
public class algo3 { public static void main(String[] args){ basic11 b=new basic11();
process11 p=new process11(b); process22 k=new process22(b);
try{
Thread.sleep(1);
}catch(Exception e)
{System.out.println("Exception caught 3 "+e);
}
System.out.println("Calling to stop the execution of Threads");
p.stopi();
k.t.join();
}catch(Exception e)
{
System.out.println("Exception Caught");
}
System.out.println("Main Thread Exiting");
66
17103067 CSX-325
}
}
67
17103067 CSX-325
LAB 17
AIM: To implement Bakery algorithm.
package os;
public class Bakery extends Thread { public int thread_id;
public static final int countToThis = 200; public static final int numberOfThreads = 5; public
static volatile int count = 0;
private static volatile boolean[] choosing = new boolean[numberOfThreads]
private static volatile int[] ticket = new int[numberOfThreads]; public Bakery(int id) {
thread_id = id;
} public void run() { int scale = 2;
for (int i = 0; i < countToThis; i++) { lock(thread_id); count = count + 1;
System.out.println("I am " + thread_id + " and count is: " + count); try {
sleep((int) (Math.random() * scale));
} catch (InterruptedException e) { /* nothing */ } unlock(thread_id);
} } public void lock(int id) { choosing[id] = true; ticket[id] = findMax() + 1; choosing[id] = false;
for (int j = 0; j < numberOfThreads; j++) { if (j == id) continue; while (choosing[j]) { }
while (ticket[j] != 0 && (ticket[id] > ticket[j] || (ticket[id] == ticket[j] && id > j))) {}
}}
private void unlock(int id) {
ticket[id] = 0;
}
private int findMax() { int m = ticket[0];
for (int i = 1; i < ticket.length; i++) { if (ticket[i] > m) m = ticket[i];
} return m; } public static void main(String[] args) { for (int i = 0; i < numberOfThreads; i++) {
choosing[i] = false; ticket[i] = 0;
}
Bakery[] threads = new Bakery[numberOfThreads];
for (int i = 0; i < threads.length; i++) {
threads[i] = new Bakery(i);
threads[i].start();
68
17103067 CSX-325
}
for (int i = 0; i < threads.length; i++) { try {
threads[i].join();
} catch (InterruptedException e) { e.printStackTrace();
}
}
System.out.println("\nCount is: " + count);
System.out.println("\nExpected was: " + (countToThis * numberOfThreads));
}
}
69
17103067 CSX-325
LAB-18
AIM: To implement FIFO Page Replacement Policy
#include<stdio.h>
int main()
{
int reference_string[10], page_faults = 0, m, n, s, pages, frames;
printf("\nEnter Total Number of Pages:\t");
scanf("%d", &pages);
printf("\nEnter values of Reference String:\n");
for(m = 0; m < pages; m++)
{
printf("Value No. [%d]:\t", m + 1);
scanf("%d", &reference_string[m]);
}
printf("\nEnter Total Number of Frames:\t");
{
scanf("%d", &frames);
}
int temp[frames];
for(m = 0; m < frames; m++)
{
temp[m] = -1;
}
for(m = 0; m < pages; m++)
{
s = 0;
for(n = 0; n < frames; n++)
{
if(reference_string[m] == temp[n])
70
17103067 CSX-325
{
s++;
page_faults--;
}
}
page_faults++;
if((page_faults <= frames) && (s == 0))
{
temp[m] = reference_string[m];
}
else if(s == 0)
{
temp[(page_faults - 1) % frames] = reference_string[m];
}
printf("\n");
for(n = 0; n < frames; n++)
{
printf("%d\t", temp[n]);
}
}
printf("\nTotal Page Faults:\t%d\n", page_faults);
return 0;
}
71
17103067 CSX-325
72
17103067 CSX-325
LAB 19
AIM: To implement LRU Page Replacement Policy
#include<bits/stdc++.h>
using namespace std;
int pageFaults(int pages[], int n, int capacity)
{
set<int> s;
map<int , int> indexes;
int page_faults = 0;
for (int i=0; i<n; i++)
{
if (s.size() < capacity)
{
if (s.find(pages[i])==s.end())
{
s.insert(pages[i]);
page_faults++;
}
indexes[pages[i]] = i;
}
else
{
if (s.find(pages[i]) == s.end())
{
int lru = INT_MAX, val;
set<int>::iterator it;
for ( it=s.begin(); it!=s.end(); it++)
{
if (indexes[*it] < lru)
73
17103067 CSX-325
{
lru = indexes[*it];
val = *it;
}
}
s.erase(val);
s.insert(pages[i]);
page_faults++;
}
indexes[pages[i]] = i;
}
}
return page_faults;
}
int main()
{
int n;
cout<<"enter no. of pages: ";
cin>>n;
int pages[n];
cout<<"enter page numbers\n";
for(int i=0; i<n; i++)
cin>>pages[i];
int capacity;
cout<<"enter capacity: ";
cin>>capacity;
cout << pageFaults(pages, n, capacity);
return 0;
}
74
17103067 CSX-325
75
17103067 CSX-325
LAB-20
AIM: To implement Optimal Page Replacement Policy
#include <bits/stdc++.h>
using namespace std;
bool search(int key, vector<int>& fr)
{
for (int i = 0; i < fr.size(); i++)
if (fr[i] == key)
return true;
return false;
}
int predict(int pg[], vector<int>& fr, int pn, int index)
{
int res = -1, farthest = index;
for (int i = 0; i < fr.size(); i++)
{
int j;
for (j = index; j < pn; j++)
{
if (fr[i] == pg[j])
{
if (j > farthest)
{
farthest = j;
res = i;
}
break;
}
}
if (j == pn)
76
17103067 CSX-325
return i;
}
return (res == -1) ? 0 : res;
}
77
17103067 CSX-325
int pages[n];
cout<<"enter page numbers\n";
for(int i=0; i<n; i++)
cin>>pages[i];
int capacity;
cout<<"enter capacity: ";
cin>>capacity;
optimalPage(pages, n, capacity);
return 0;
}
78