0% found this document useful (0 votes)
30 views

OS Lab File

Uploaded by

Jayant Jha
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)
30 views

OS Lab File

Uploaded by

Jayant Jha
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/ 63

PROGRAM-1

Aim: Write a program to implement CPU scheduling for first come first serve.

Code:
#include <iostream>
using namespace std;
int main()
{
int n, bt[20], wt[20], tat[20], avwt = 0, avtat = 0, i, j;
cout << "Enter total number of processes(maximum 20):";
cin >> n;
cout << "\nEnter Process Burst Time\n";
for (i = 0; i < n; i++)
{
cout << "P[" << i + 1 << "]:";
cin >> bt[i];
}
wt[0] = 0;
for (i = 1; i < n; i++)
{
wt[i] = 0;
for (j = 0; j < i; j++)
wt[i] += bt[j];
}
cout << "\nProcess\t\tBurst Time\tWaiting Time\tTurnaround Time";
for (i = 0; i < n; i++)
{
tat[i] = bt[i] + wt[i];
avwt += wt[i];
avtat += tat[i];
cout << "\nP[" << i + 1 << "]" << "\t\t" << bt[i] << "\t\t" << wt[i] << "\t\t" << tat[i];
}
avwt /= i;
avtat /= i;
cout << "\n\nAverage Waiting Time:" << avwt;
cout << "\nAverage Turnaround Time:" << avtat;
return 0;
}
Output:
PROGRAM-2

Aim: Write a program to implement CPU scheduling for shortest job first.

Code:
#include <iostream>
using namespace std;
int mat[10][6];
void swap(int *a, int *b)
{
int temp = *a;
*a = *b;
*b = temp;
}
void arrangeArrival(int num, int mat[][6])
{
for (int i = 0; i < num; i++)
{
for (int j = 0; j < num - i - 1; j++)
{
if (mat[j][1] > mat[j + 1][1])
{
for (int k = 0; k < 5; k++)
{
swap(mat[j][k], mat[j + 1][k]);
}
}
}
}
}
void completionTime(int num, int mat[][6])
{

int temp, val;


mat[0][3] = mat[0][1] + mat[0][2];
mat[0][5] = mat[0][3] - mat[0][1];
mat[0][4] = mat[0][5] - mat[0][2];
for (int i = 1; i < num; i++)
{
temp = mat[i - 1][3];
int low = mat[i][2];
for (int j = i; j < num; j++)
{
if (temp >= mat[j][1] && low >= mat[j][2])
{
low = mat[j][2];
val = j;
}
}
mat[val][3] = temp + mat[val][2];
mat[val][5] = mat[val][3] - mat[val][1];
mat[val][4] = mat[val][5] - mat[val][2];
for (int k = 0; k < 6; k++)
{
swap(mat[val][k], mat[i][k]);
}
}
}
int main()
{
int num, temp;
cout << "Enter number of Process: ";
cin >> num;
cout << "...Enter the process ID...\n";
for (int i = 0; i < num; i++)
{
cout << "...Process " << i + 1 << "...\n";
cout << "Enter Process Id: ";
cin >> mat[i][0];
cout << "Enter Arrival Time: ";
cin >> mat[i][1];
cout << "Enter Burst Time: ";
cin >> mat[i][2];
}
cout << "Before Arrange...\n";
cout << "Process ID\tArrival Time\tBurst Time\n";
for (int i = 0; i < num; i++)
{
cout << mat[i][0] << "\t\t" << mat[i][1] << "\t\t" << mat[i][2] << "\n";
}
arrangeArrival(num, mat);
completionTime(num, mat);
cout << "Final Result...\n";
cout << "Process ID\tArrival Time\tBurst Time\tWaiting Time\tTurnaround
Time\n";
for (int i = 0; i < num; i++)
{
cout << mat[i][0] << "\t\t" << mat[i][1] << "\t\t" << mat[i][2] << "\t\t" << mat[i][4]
<< "\t\t" << mat[i][5] << "\n";
}
}
Output:
PROGRAM-3

Aim: Write a program to perform preemptive priority scheduling.

Code:
#include <iostream>
using namespace std;
int main()
{
int bt[20], p[20], wt[20], tat[20], pr[20], i, j, n, total = 0, pos, temp, avg_wt,
avg_tat;
cout << "Enter Total Number of Process:";
cin >> n;
cout << "\nEnter Burst Time and Priority\n";
for (i = 0; i < n; i++)
{
cout << "\nP[" << i + 1 << "]\n";
cout << "Burst Time:";
cin >> bt[i];
cout << "Priority:";
cin >> pr[i];
p[i] = i + 1;
}

// Sorting based on priority


for (i = 0; i < n; i++)
{
pos = i;
for (j = i + 1; j < n; j++)
{
if (pr[j] < pr[pos])
{
pos = j;
}
}

// Swapping burst times, priorities and process numbers


temp = pr[i];
pr[i] = pr[pos];
pr[pos] = temp;
temp = bt[i];
bt[i] = bt[pos];
bt[pos] = temp;
temp = p[i];
p[i] = p[pos];
p[pos] = temp;
}

// Waiting time for first process is 0


wt[0] = 0;

// Calculating waiting time


for (i = 1; i < n; i++)
{
wt[i] = 0;
for (j = 0; j < i; j++)
wt[i] += bt[j];
total += wt[i];
}
avg_wt = total / n;
total = 0;

cout << "\nProcess\t Burst Time \tWaiting Time\tTurnaround Time";

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


{
tat[i] = bt[i] + wt[i];
total += tat[i];
cout << "\nP[" << p[i] << "]\t\t " << bt[i] << "\t\t " << wt[i] << "\t\t\t" << tat[i];
}
avg_tat = total / n;

cout << "\n\nAverage Waiting Time=" << avg_wt;


cout << "\nAverage Turnaround Time=" << avg_tat;

return 0;
}
Output:
PROGRAM-4

Aim: Write a program to implement CPU scheduling for Round Robin.

Code:
#include <iostream>
#include <vector>
#include <queue>
#include <iomanip>

using namespace std;

struct Process
{
int pid; // Process ID
int arrival; // Arrival Time
int burst; // Burst Time
int remaining; // Remaining Burst Time
int completion; // Completion Time
int turnaround; // Turnaround Time
int waiting; // Waiting Time
};

// Function to perform Round Robin Scheduling


void roundRobinScheduling(vector<Process> &processes, int quantum)
{
int currentTime = 0;
queue<int> readyQueue;
int totalProcesses = processes.size();
int completed = 0;

// A flag array to check if a process has been added to the queue


vector<bool> inQueue(totalProcesses, false);

// Push initial processes that arrive at time 0


for (int i = 0; i < totalProcesses; i++)
{
if (processes[i].arrival == 0)
{
readyQueue.push(i);
inQueue[i] = true;
}
}

while (completed < totalProcesses)


{
if (!readyQueue.empty())
{
int currentProcessIndex = readyQueue.front();
readyQueue.pop();

Process &currentProcess = processes[currentProcessIndex];


// Execute the process for the quantum or its remaining burst time
int timeSlice = min(quantum, currentProcess.remaining);
currentProcess.remaining -= timeSlice;
currentTime += timeSlice;

// If process completes, calculate completion, turnaround, and waiting


times
if (currentProcess.remaining == 0)
{
completed++;
currentProcess.completion = currentTime;
currentProcess.turnaround = currentProcess.completion -
currentProcess.arrival;
currentProcess.waiting = currentProcess.turnaround -
currentProcess.burst;
}

// Add processes that arrive during execution to the ready queue


for (int i = 0; i < totalProcesses; i++)
{
if (!inQueue[i] && processes[i].arrival <= currentTime &&
processes[i].remaining > 0)
{
readyQueue.push(i);
inQueue[i] = true;
}
}

// If current process is not finished, add it back to the ready queue


if (currentProcess.remaining > 0)
{
readyQueue.push(currentProcessIndex);
}
}
else
{
// If no processes are ready, increment the current time
currentTime++;
// Add newly arrived processes
for (int i = 0; i < totalProcesses; i++)
{
if (!inQueue[i] && processes[i].arrival <= currentTime &&
processes[i].remaining > 0)
{
readyQueue.push(i);
inQueue[i] = true;
}
}
}
}
}

// Function to display the result table


void displayResultTable(const vector<Process> &processes)
{
cout << "\n+-------------------------------------------------------------------+\n";
cout << "| Process | Arrival | Burst | Completion | Turnaround | Waiting Time
|\n";
cout << "+-------------------------------------------------------------------+\n";

for (const auto &p : processes)


{
cout << "| P" << setw(3) << p.pid << setw(5)
<< "| " << setw(4) << p.arrival << setw(5)
<< "| " << setw(4) << p.burst << setw(5)
<< "| " << setw(7) << p.completion << setw(7)
<< "| " << setw(7) << p.turnaround << setw(9)
<< "| " << setw(7) << p.waiting << setw(7) << "|\n";
}

cout << "+-------------------------------------------------------------------+\n";


}

int main()
{
int n, quantum;

// Get number of processes and quantum


cout << "Enter the number of processes: ";
cin >> n;
vector<Process> processes(n);

// Get process details (arrival time, burst time)


for (int i = 0; i < n; i++)
{
processes[i].pid = i + 1;
cout << "Enter Arrival time for process P" << processes[i].pid << ": ";
cin >> processes[i].arrival;
cout << "Enter Burst time for process P" << processes[i].pid << ": ";
cin >> processes[i].burst;
processes[i].remaining = processes[i].burst; // Initialize remaining burst time
}

cout << "Enter Quantum time: ";


cin >> quantum;

// Call the round robin scheduling function


roundRobinScheduling(processes, quantum);

// Display the result table


displayResultTable(processes);

// Calculate average waiting time and average turnaround time


float totalWaitingTime = 0;
float totalTurnaroundTime = 0;
for (const auto &p : processes)
{
totalWaitingTime += p.waiting;
totalTurnaroundTime += p.turnaround;
}

cout << fixed << setprecision(2); // Set precision for floating point output
cout << "\nAverage Waiting Time: " << totalWaitingTime / n << endl;
cout << "Average Turnaround Time: " << totalTurnaroundTime / n << endl;

return 0;
}
Output:
PROGRAM-5

Aim: Write a program to implement CPU scheduling for preemptive Shortest Time
First (SRTF).

Code:
#include <iostream>
#include <climits> // For INT MAX
using namespace std;

int main()
{

int n, i, smallest, time = 0, endTime;


int at[20], bt[20], rem_bt[20], wt[20], tat[20], ct[20]; // Arrays for arrival tine,
burst time, etc.

float avg_wt = 0, avg_tat = 0;


bool process_done = false;

cout << "Enter Total number of Processes:";


cin >> n;

cout << "Enter Arrival Time and Burst Time for each process \n";
for (i = 0; i < n; i++)
{
cout << "Process P" << i + 1 << " Arrival Time: ";
cin >> at[i];
cout << "Process P" << i + 1 << " Burst Time: ";
cin >> bt[i];
rem_bt[i] = bt[i]; // Initialize remaining burst time as burst time
}

int total_completed = 0, current_time = 0, min_remaining_time = INT_MAX;


int shortest = 0, finish_time;
bool check = false;

// Process until all processes get completed


while (total_completed != n)
{
// Find the process with minimum remaining time
for (i = 0; i < n; i++)
{
if ((at[i] <= current_time) && (rem_bt[i] < min_remaining_time) && rem_bt[i]
> 0)
{
min_remaining_time = rem_bt[i];
shortest = i;
check = true;
}
}

if (!check)
{
current_time++;
continue;
}

// Reduce remaining time by one unit


rem_bt[shortest]--;

// Update minimum remaining time


min_remaining_time = rem_bt[shortest];
if (min_remaining_time == 0)
{
min_remaining_time = INT_MAX;
}

// If a process gets completely executed


if (rem_bt[shortest] == 0)
{
total_completed++;
check = false;

// Completion time for the current process


finish_time = current_time + 1;
ct[shortest] = finish_time;
// Calculate waiting time and turnaround time
tat[shortest] = ct[shortest] - at[shortest]; // Turnaround time = Completion
time - Arrival time
wt[shortest] = tat[shortest] - bt[shortest]; // Waiting time = Turnaround time -
Burst time

avg_wt += wt[shortest]; // Sum of waiting times


avg_tat += tat[shortest]; // Sum of turnaround times
}

// Increment time
current_time++;
}

avg_wt != n;
avg_tat != n;

// Output the results


cout << "\nProcess\tArrival Time\tBurst Time\tCompletion Time\tWaiting
Time\tTurnaround Time\n";

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


{
cout << "P[" << i + 1 << "]\t" << at[i] << "\t\t" << "bt[i]" << "\t\t" << ct[i] << "\t\t"
<< wt[i] << "\t\t" << tat[i] << "\n";
}
cout << "\nAverage waiting Time = " << avg_wt;
cout << "\nAverage Turnaround Time = " << avg_tat;

return 0;
}
Output:
PROGRAM-6

Aim: Write a program for page replacement policy using a) LRU b) FIFO c) Optimal

6.1: LRU (Least Recently Used)


Code:
#include <iostream>
#include <vector>
#include <unordered_map>
#include <algorithm> // Include this for std::find

using namespace std;

void LRU(vector<int> &pages, int frames)


{
vector<int> memory(frames, -1);
unordered_map<int, int> lruMap; // stores last used time
int page_faults = 0, hits = 0;

for (int i = 0; i < pages.size(); i++)


{
auto it = find(memory.begin(), memory.end(), pages[i]); // std::find is used to
search

if (it == memory.end())
{ // Page fault
page_faults++;
int least_recent = i, lru_index = 0;
for (int j = 0; j < frames; j++)
{
if (memory[j] == -1)
{
lru_index = j;
break;
}
if (lruMap[memory[j]] < least_recent)
{
least_recent = lruMap[memory[j]];
lru_index = j;
}
}
memory[lru_index] = pages[i];
}
else
{
hits++;
}
lruMap[pages[i]] = i; // Update last used
}

cout << "LRU - Hits: " << hits << ", Page Faults: " << page_faults << "\n";
cout << "Hit percentage: " << (double)hits / pages.size() * 100 << "%\n";
cout << "Fault percentage: " << (double)page_faults / pages.size() * 100 <<
"%\n";
}

int main()
{
int n, frames;
cout << "Enter the number of pages: ";
cin >> n;

vector<int> pages(n);
cout << "Enter the page sequence:\n";
for (int i = 0; i < n; i++)
{
cin >> pages[i];
}

cout << "Enter the number of frames: ";


cin >> frames;

LRU(pages, frames);

return 0;
}
Output:
6.2: FIFO (First in First Out)
Code:
#include <iostream>
#include <vector>
#include <algorithm>
using namespace std;

void FIFO(vector<int> &pages, int frames)


{
vector<int> memory(frames, -1);
int page_faults = 0, hits = 0, next_frame = 0;

for (int i = 0; i < pages.size(); i++)


{
auto it = find(memory.begin(), memory.end(), pages[i]);

if (it == memory.end())
{ // Page fault
page_faults++;
memory[next_frame] = pages[i];
next_frame = (next_frame + 1) % frames; // FIFO rotation
}
else
{
hits++;
}
}

cout << "FIFO - Hits: " << hits << ", Page Faults: " << page_faults << "\n";
cout << "Hit percentage: " << (double)hits / pages.size() * 100 << "%\n";
cout << "Fault percentage: " << (double)page_faults / pages.size() * 100 <<
"%\n";
}

int main(){
int n, frames;
cout << "Enter the number of pages: ";
cin >> n;

vector<int> pages(n);
cout << "Enter the page sequence:\n";
for (int i = 0; i < n; i++)
{
cin >> pages[i];
}

cout << "Enter the number of frames: ";


cin >> frames;

FIFO(pages, frames);

return 0;
}
Output:
6.3: Optimal
Code:
#include <iostream>
#include <vector>
#include <algorithm>
using namespace std;

int predict(vector<int> &pages, vector<int> &memory, int index)


{
int farthest = index, mem_index = -1;
for (int i = 0; i < memory.size(); i++)
{
int j;
for (j = index; j < pages.size(); j++)
{
if (memory[i] == pages[j])
{
if (j > farthest)
{
farthest = j;
mem_index = i;
}
break;
}
}
if (j == pages.size())
{
return i;
}
}
return (mem_index == -1) ? 0 : mem_index;
}

void Optimal(vector<int> &pages, int frames)


{
vector<int> memory(frames, -1);
int page_faults = 0, hits = 0;

for (int i = 0; i < pages.size(); i++)


{
auto it = find(memory.begin(), memory.end(), pages[i]);

if (it == memory.end())
{ // Page fault
page_faults++;
if (find(memory.begin(), memory.end(), -1) != memory.end())
{
*find(memory.begin(), memory.end(), -1) = pages[i];
}
else
{
int replace_index = predict(pages, memory, i + 1);
memory[replace_index] = pages[i];
}
}
else
{
hits++;
}
}

cout << "Optimal - Hits: " << hits << ", Page Faults: " << page_faults << "\n";
cout << "Hit percentage: " << (double)hits / pages.size() * 100 << "%\n";
cout << "Fault percentage: " << (double)page_faults / pages.size() * 100 <<
"%\n";
}

int main()
{
int n, frames;
cout << "Enter the number of pages: ";
cin >> n;

vector<int> pages(n);
cout << "Enter the page sequence:\n";
for (int i = 0; i < n; i++)
{
cin >> pages[i];
}
cout << "Enter the number of frames: ";
cin >> frames;

Optimal(pages, frames);

return 0;
}
Output:
PROGRAM-7

Aim: Write a program to implement first fit, best fit and worst fit algorithm for
memory management.

7.1: First Fit


Code:
#include <iostream>
#include <vector>

using namespace std;

void firstFit(const vector<int> &memory, const vector<int> &processes)


{
vector<bool> allocated(memory.size(), false);

for (int i = 0; i < processes.size(); i++)


{
bool allocatedFlag = false;
for (size_t j = 0; j < memory.size(); j++)
{
if (!allocated[j] && memory[j] >= processes[i])
{
allocated[j] = true;
cout << "First Fit: Allocated process of size " << processes[i]
<< " in block of size " << memory[j] << " (Block " << j + 1 << ")" << endl;
allocatedFlag = true;
break;
}
}
if (!allocatedFlag)
{
cout << "First Fit: No suitable block found for process of size " <<
processes[i] << endl;
}
}
}

int main()
{
int n;

// User input for memory blocks


cout << "Enter the number of memory blocks: ";
cin >> n;
vector<int> memory(n);

cout << "Enter the sizes of memory blocks:\n";


for (int i = 0; i < n; i++)
{
cout << "Block " << i + 1 << ": ";
cin >> memory[i];
}
int m;

// User input for processes


cout << "Enter the number of processes: ";
cin >> m;
vector<int> processes(m);

cout << "Enter the sizes of processes:\n";


for (int i = 0; i < m; i++)
{
cout << "Process " << i + 1 << ": ";
cin >> processes[i];
}

firstFit(memory, processes);

return 0;
}
Output:
7.2: Best Fit
Code:
#include <iostream>
#include <vector>
#include <climits>

using namespace std;

void bestFit(const vector<int> &memory, const vector<int> &processes)


{
vector<bool> allocated(memory.size(), false);

for (int i = 0; i < processes.size(); i++)


{
int bestIndex = -1;
int bestSize = INT_MAX;

for (size_t j = 0; j < memory.size(); j++)


{
if (!allocated[j] && memory[j] >= processes[i] && memory[j] < bestSize)
{
bestSize = memory[j];
bestIndex = j;
}
}
if (bestIndex != -1)
{
allocated[bestIndex] = true;
cout << "Best Fit: Allocated process of size " << processes[i]
<< " in block of size " << memory[bestIndex] << " (Block " << bestIndex + 1
<< ")" << endl;
}
else
{
cout << "Best Fit: No suitable block found for process of size " <<
processes[i] << endl;
}
}
}

int main()
{
int n;

// User input for memory blocks


cout << "Enter the number of memory blocks: ";
cin >> n;
vector<int> memory(n);

cout << "Enter the sizes of memory blocks:\n";


for (int i = 0; i < n; i++)
{
cout << "Block " << i + 1 << ": ";
cin >> memory[i];
}

int m;

// User input for processes


cout << "Enter the number of processes: ";
cin >> m;
vector<int> processes(m);

cout << "Enter the sizes of processes:\n";


for (int i = 0; i < m; i++)
{
cout << "Process " << i + 1 << ": ";
cin >> processes[i];
}

bestFit(memory, processes);

return 0;
}
Output:
7.3: Worst Fit
Code:
#include <iostream>
#include <vector>

using namespace std;

void worstFit(const vector<int> &memory, const vector<int> &processes)


{
vector<bool> allocated(memory.size(), false);

for (int i = 0; i < processes.size(); i++)


{
int worstIndex = -1;
int worstSize = -1;

for (size_t j = 0; j < memory.size(); j++)


{
if (!allocated[j] && memory[j] >= processes[i] && memory[j] > worstSize)
{
worstSize = memory[j];
worstIndex = j;
}
}

if (worstIndex != -1)
{
allocated[worstIndex] = true;
cout << "Worst Fit: Allocated process of size " << processes[i]
<< " in block of size " << memory[worstIndex] << " (Block " << worstIndex +
1 << ")" << endl;
}
else
{
cout << "Worst Fit: No suitable block found for process of size " <<
processes[i] << endl;
}
}
}

int main()
{
int n;

// User input for memory blocks


cout << "Enter the number of memory blocks: ";
cin >> n;
vector<int> memory(n);

cout << "Enter the sizes of memory blocks:\n";


for (int i = 0; i < n; i++)
{
cout << "Block " << i + 1 << ": ";
cin >> memory[i];
}

int m;

// User input for processes


cout << "Enter the number of processes: ";
cin >> m;
vector<int> processes(m);

cout << "Enter the sizes of processes:\n";


for (int i = 0; i < m; i++)
{
cout << "Process " << i + 1 << ": ";
cin >> processes[i];
}

worstFit(memory, processes);

return 0;
}
Output:
PROGRAM-9

Aim: Write a program to implement reader/writer problem using semaphore


Code:
#include <iostream>
using namespace std;

int main()
{
int bu er[10], bufsize, in, out, produce, choice = 0;
in = 0;
out = 0;
bufsize = 10;

while (choice != 3)
{
cout << "\n1. Produce \t 2. Consume \t 3. Exit";
cout << "\nEnter your choice: ";
cin >> choice;

switch (choice)
{
case 1:
if ((in + 1) % bufsize == out)
{
cout << "\nBu er is Full";
}
else
{
cout << "\nEnter the value: ";
cin >> produce;
bu er[in] = produce;
in = (in + 1) % bufsize;
cout << "\nProduced: " << produce;
}
break; // Fixed 'Break' to 'break'

case 2:
if (in == out)
{
cout << "\nBu er is Empty";
}
else
{
cout << "\nConsumed: " << bu er[out];
out = (out + 1) % bufsize;
}
break; // Added break statement for case 2

case 3:
cout << "\nExiting...";
break; // Handle exit option
default:
cout << "\nInvalid choice. Please try again.";
}
}

return 0;
}
Output:
PROGRAM-10

Aim: Write a program to implement Banker’s algorithm for deadlock avoidance.


Code:
#include <iostream>
#include <vector>

using namespace std;

int main()
{
int alloc[10][10], max[10][10];
int avail[10], work[10], total[10];
int need[10][10];
int finish[10] = {0}; // Array to mark if a process is finished
int n, m, count = 0, c = 0;

cout << "Enter the number of processes and resources: ";


cin >> n >> m;

cout << "Enter the claim matrix:\n";


for (int i = 0; i < n; i++)
for (int j = 0; j < m; j++)
cin >> max[i][j];

cout << "Enter the allocation matrix:\n";


for (int i = 0; i < n; i++)
for (int j = 0; j < m; j++)
cin >> alloc[i][j];

cout << "Enter the resource vector: ";


for (int i = 0; i < m; i++)
cin >> total[i];

// Calculate available resources


for (int i = 0; i < m; i++)
avail[i] = 0;
for (int i = 0; i < n; i++)
for (int j = 0; j < m; j++)
avail[j] += alloc[i][j];

for (int i = 0; i < m; i++)


work[i] = total[i] - avail[i];

// Calculate the need matrix


for (int i = 0; i < n; i++)
for (int j = 0; j < m; j++)
need[i][j] = max[i][j] - alloc[i][j];

// Banker's Algorithm
while (count < n)
{
bool allocated = false;
for (int i = 0; i < n; i++)
{
c = 0;
for (int j = 0; j < m; j++)
{
if (need[i][j] <= work[j] && !finish[i])
c++;
}
if (c == m)
{ // If all resources can be allocated to process i
cout << "All the resources can be allocated to Process " << i + 1 << endl;
cout << "Available resources are: ";
for (int k = 0; k < m; k++)
{
work[k] += alloc[i][k];
cout << work[k] << " ";
}
cout << endl;
finish[i] = 1;
cout << "Process " << i + 1 << " executed? " << (finish[i] ? 'y' : 'n') << endl;
count++;
allocated = true;
}
}
if (!allocated)
break; // If no allocation was possible, break the loop
}

if (count == n)
cout << "\nSystem is in a safe mode\nThe given state is a safe state" << endl;
else
cout << "\nSystem is not in a safe mode" << endl;

return 0;
}
Output:
PROGRAM-8

Aim: Write a program to implement reader/writer problem using semaphore.


Code:
#include <iostream>
#include <windows.h>

using namespace std;

HANDLE x, y;
int readerCount = 0;

DWORD WINAPI reader(LPVOID param)


{
WaitForSingleObject(x, INFINITE);
readerCount++;
if (readerCount == 1)
{
WaitForSingleObject(y, INFINITE); // First reader locks the writer semaphore
}
ReleaseSemaphore(x, 1, NULL);

cout << readerCount << " reader is inside" << endl;

WaitForSingleObject(x, INFINITE);
readerCount--;
if (readerCount == 0)
{
ReleaseSemaphore(y, 1, NULL); // Last reader unlocks the writer semaphore
}
ReleaseSemaphore(x, 1, NULL);

cout << readerCount + 1 << " reader is leaving" << endl;


return 0;
}

DWORD WINAPI writer(LPVOID param)


{
cout << "Writer is trying to enter" << endl;
WaitForSingleObject(y, INFINITE); // Writer locks the writer semaphore
cout << "Writer has entered" << endl;
ReleaseSemaphore(y, 1, NULL); // Writer unlocks the writer semaphore
cout << "Writer is leaving" << endl;
return 0;
}

int main()
{
int numReaders;
cout << "Enter the number of readers: ";
cin >> numReaders;
// Initialize semaphores
x = CreateSemaphore(NULL, 1, 1, NULL);
y = CreateSemaphore(NULL, 1, 1, NULL);

// Create reader and writer threads


HANDLE readerThreads[100], writerThreads[100];
for (int i = 0; i < numReaders; i++)
{
readerThreads[i] = CreateThread(NULL, 0, reader, NULL, 0, NULL);
writerThreads[i] = CreateThread(NULL, 0, writer, NULL, 0, NULL);
}

// Wait for all threads to finish


WaitForMultipleObjects(numReaders, readerThreads, TRUE, INFINITE);
WaitForMultipleObjects(numReaders, writerThreads, TRUE, INFINITE);

// Close handles
CloseHandle(x);
CloseHandle(y);

return 0;
}
Output:

You might also like