0% found this document useful (0 votes)
3 views35 pages

Os Lab Pratical Full - Repaired

The document outlines five experiments related to CPU scheduling algorithms, including First-Come-First-Serve (FCFS), Shortest Job First (SJF), Priority Scheduling, Round Robin (RR), and Deadlock detection. Each experiment provides an algorithm and a C++ program implementation to calculate waiting time, turnaround time, and average times for various processes. The experiments aim to demonstrate different scheduling techniques and their respective outcomes in managing CPU processes.

Uploaded by

aniketrajpoot352
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)
3 views35 pages

Os Lab Pratical Full - Repaired

The document outlines five experiments related to CPU scheduling algorithms, including First-Come-First-Serve (FCFS), Shortest Job First (SJF), Priority Scheduling, Round Robin (RR), and Deadlock detection. Each experiment provides an algorithm and a C++ program implementation to calculate waiting time, turnaround time, and average times for various processes. The experiments aim to demonstrate different scheduling techniques and their respective outcomes in managing CPU processes.

Uploaded by

aniketrajpoot352
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/ 35

SAGAR INSTITUTE OF RESEARCH AND TECHNOLOGY

EXPERIMENT 1

AIM: Program to implement FCFS CPU scheduling algorithm.


Algorithm:

1. Start the process

2. Get the number of processes to be inserted

3. Get the value for burst time of each process from the user

4. Having allocated the burst time(bt) for individual processes , Start with the first process
from it’s initial position let other process to be in queue

5. Calculate the waiting time(wt) and turnaround time(tat) as

Wt(pi) = wt(pi-1) + tat(pi-1) (i.e wt of current process = wt of previous process + tat of


previous process)

tat(pi) = wt(pi) + bt(pi) (i.e tat of current process = wt of current process + bt of current
process)

6. Calculate the total and average waiting time and turnaround time

7. Display the values

8. Stop the process

Program:

#include<iostream.h>
#include<conio.h>

using namespace std;

// Function to find the waiting time for all


// processes
void findWaitingTime(int processes[], int n, int bt[], int wt[])
{
// waiting time for first process is 0
wt[0] = 0;

// calculating waiting time


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

// Function to calculate turn around time


void findTurnAroundTime( int processes[], int n,
SAGAR INSTITUTE OF RESEARCH AND TECHNOLOGY

int bt[], int wt[], int tat[])


{
// calculating turnaround time by adding
// bt[i] + wt[i]
for (int i = 0; i < n ; i++)
tat[i] = bt[i] + wt[i];
}

//Function to calculate average time


void findavgTime( int processes[], int n, int bt[])
{
int wt[n], tat[n], total_wt = 0, total_tat = 0;

//Function to find waiting time of all processes


findWaitingTime(processes, n, bt, wt);

//Function to find turn around time for all processes


findTurnAroundTime(processes, n, bt, wt, tat);

//Display processes along with all details


cout << "Processes "<< " Burst time "
<< " Waiting time " << " Turn around time\n";

// Calculate total waiting time and total turn


// around time
for (int i=0; i<n; i++)
{
total_wt = total_wt + wt[i];
total_tat = total_tat + tat[i];
cout << " " << i+1 << "\t\t" << bt[i] <<"\t "
<< wt[i] <<"\t\t " << tat[i] <<endl;
}

cout << "Average waiting time = "


<< (float)total_wt / (float)n;
cout << "\nAverage turn around time = "
<< (float)total_tat / (float)n;
}

// Driver code
int main()
{
//process id's
int processes[] = { 1, 2, 3};
int n = sizeof processes / sizeof processes[0];

//Burst time of all processes


int burst_time[] = {10, 5, 8};

findavgTime(processes, n, burst_time);
return 0;
}
SAGAR INSTITUTE OF RESEARCH AND TECHNOLOGY
SAGAR INSTITUTE OF RESEARCH AND TECHNOLOGY

EXPERIMENT 2
Algorithm:

1. Start the process

2. Get the number of processes to be inserted

3. Sort the processes according to the burst time and allocate the one with shortest burst to
execute first

4. If two processes have same burst length then FCFS scheduling algorithm is used

5. Calculate the total and average waiting time and turnaround time

6. Display the values

7. Stop the process

Program:
// C++ program to implement Shortest Job first with Arrival
// Time
#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]);
}
}
}
}
SAGAR INSTITUTE OF RESEARCH AND TECHNOLOGY

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];
SAGAR INSTITUTE OF RESEARCH AND TECHNOLOGY

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
SAGAR INSTITUTE OF RESEARCH AND TECHNOLOGY

EXPERIMENT 3

AIM: Program to implement Priority CPU Scheduling algorithm.

Algorithm:

1. Start the process

2. Get the number of processes to be inserted

3. Get the corresponding priority of processes

4. Sort the processes according to the priority and allocate the one with highest priority to
execute first

5. If two process have same priority then FCFS scheduling algorithm is used

6. Calculate the total and average waiting time and turnaround time

7. Display the values

8. Stop the process

Program:

// C++ program for implementation of FCFS


// scheduling
#include<bits/stdc++.h>
using namespace std;

struct Process
{
int pid; // Process ID
int bt; // CPU Burst time required
int priority; // Priority of this process
};

// Function to sort the Process acc. to priority


bool comparison(Process a, Process b)
{
return (a.priority > b.priority);
}
SAGAR INSTITUTE OF RESEARCH AND TECHNOLOGY

// Function to find the waiting time for all


// processes
void findWaitingTime(Process proc[], int n,
int wt[])
{
// waiting time for first process is 0
wt[0] = 0;

// calculating waiting time


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

// Function to calculate turn around time


void findTurnAroundTime( Process proc[], int n,
int wt[], int tat[])
{
// calculating turnaround time by adding
// bt[i] + wt[i]
for (int i = 0; i < n ; i++)
tat[i] = proc[i].bt + wt[i];
}

//Function to calculate average time


void findavgTime(Process proc[], int n)
{
int wt[n], tat[n], total_wt = 0, total_tat = 0;

//Function to find waiting time of all processes


findWaitingTime(proc, n, wt);

//Function to find turn around time for all processes


findTurnAroundTime(proc, n, wt, tat);

//Display processes along with all details


cout << "\nProcesses "<< " Burst time "
<< " Waiting time " << " Turn around time\n";

// Calculate total waiting time and total turn


// around time
for (int i=0; i<n; i++)
{
SAGAR INSTITUTE OF RESEARCH AND TECHNOLOGY

total_wt = total_wt + wt[i];


total_tat = total_tat + tat[i];
cout << " " << proc[i].pid << "\t\t"
<< proc[i].bt << "\t " << wt[i]
<< "\t\t " << tat[i] <<endl;
}

cout << "\nAverage waiting time = "


<< (float)total_wt / (float)n;
cout << "\nAverage turn around time = "
<< (float)total_tat / (float)n;
}

void priorityScheduling(Process proc[], int n)


{
// Sort processes by priority
sort(proc, proc + n, comparison);

cout<< "Order in which processes gets executed \n";


for (int i = 0 ; i < n; i++)
cout << proc[i].pid <<" " ;

findavgTime(proc, n);
}

// Driver code
int main()
{
Process proc[] = {{1, 10, 2}, {2, 5, 0}, {3, 8, 1}};
int n = sizeof proc / sizeof proc[0];
priorityScheduling(proc, n);
return 0;
}
SAGAR INSTITUTE OF RESEARCH AND TECHNOLOGY

Output
SAGAR INSTITUTE OF RESEARCH AND TECHNOLOGY

EXPERIMENT 4

AIM: Program to implement Round Robin CPU scheduling algorithm.

Algorithm:

1. Start the process

2. Get the number of elements to be inserted

3. Get the value for burst time for individual processes

4. Get the value for time quantum

5. Make the CPU scheduler go around the ready queue allocating CPU to each process for the
time interval specified

6. Make the CPU scheduler pick the first process and set time to interrupt after quantum. And
after it's expiry dispatch the process

7. If the process has burst time less than the time quantum then the process is released by the
CPU

8. If the process has burst time greater than time quantum then it is interrupted by the OS and
the process is put to the tail of ready queue and the schedule selects next process from head of
the queue

9. Calculate the total and average waiting time and turnaround time

10. Display the results

11. Stop the process

Program:

// C++ program for implementation of RR scheduling


#include<iostream>
using namespace std;

// Function to find the waiting time for all


// processes
void findWaitingTime(int processes[], int n,
int bt[], int wt[], int quantum)
SAGAR INSTITUTE OF RESEARCH AND TECHNOLOGY

{
// Make a copy of burst times bt[] to store remaining
// burst times.
int rem_bt[n];
for (int i = 0 ; i < n ; i++)
rem_bt[i] = bt[i];

int t = 0; // Current time

// Keep traversing processes in round robin manner


// until all of them are not done.
while (1)
{
bool done = true;

// Traverse all processes one by one repeatedly


for (int i = 0 ; i < n; i++)
{
// If burst time of a process is greater than 0
// then only need to process further
if (rem_bt[i] > 0)
{
done = false; // There is a pending process

if (rem_bt[i] > quantum)


{
// Increase the value of t i.e. shows
// how much time a process has been processed
t += quantum;

// Decrease the burst_time of current process


// by quantum
rem_bt[i] -= quantum;
}

// If burst time is smaller than or equal to


// quantum. Last cycle for this process
else
{
// Increase the value of t i.e. shows
// how much time a process has been processed
t = t + rem_bt[i];
SAGAR INSTITUTE OF RESEARCH AND TECHNOLOGY

// Waiting time is current time minus time


// used by this process
wt[i] = t - bt[i];

// As the process gets fully executed


// make its remaining burst time = 0
rem_bt[i] = 0;
}
}
}

// If all processes are done


if (done == true)
break;
}
}

// Function to calculate turn around time


void findTurnAroundTime(int processes[], int n,
int bt[], int wt[], int tat[])
{
// calculating turnaround time by adding
// bt[i] + wt[i]
for (int i = 0; i < n ; i++)
tat[i] = bt[i] + wt[i];
}

// Function to calculate average time


void findavgTime(int processes[], int n, int bt[],
int quantum)
{
int wt[n], tat[n], total_wt = 0, total_tat = 0;

// Function to find waiting time of all processes


findWaitingTime(processes, n, bt, wt, quantum);

// Function to find turn around time for all processes


findTurnAroundTime(processes, n, bt, wt, tat);

// Display processes along with all details


cout << "Processes "<< " Burst time "
<< " Waiting time " << " Turn around time\n";
SAGAR INSTITUTE OF RESEARCH AND TECHNOLOGY

// Calculate total waiting time and total turn


// around time
for (int i=0; i<n; i++)
{
total_wt = total_wt + wt[i];
total_tat = total_tat + tat[i];
cout << " " << i+1 << "\t\t" << bt[i] <<"\t "
<< wt[i] <<"\t\t " << tat[i] <<endl;
}

cout << "Average waiting time = "


<< (float)total_wt / (float)n;
cout << "\nAverage turn around time = "
<< (float)total_tat / (float)n;
}

// Driver code
int main()
{
// process id's
int processes[] = { 1, 2, 3};
int n = sizeof processes / sizeof processes[0];

// Burst time of all processes


int burst_time[] = {10, 5, 8};

// Time quantum
int quantum = 2;
findavgTime(processes, n, burst_time, quantum);
return 0;
}

Output
SAGAR INSTITUTE OF RESEARCH AND TECHNOLOGY

EXPERIMENT 5
AIM: Program to implement Deadlock.

Program:

// C++ implementation of above program.

#include <bits/stdc++.h>

using namespace std;

// function that calculates

// the minimum no. of resources

int Resources(int process, int need)

int minResources = 0;

// Condition so that deadlock

// will not occur

minResources = process * (need - 1) + 1;

return minResources;

// Driver code

int main()

int process = 3, need = 4;


SAGAR INSTITUTE OF RESEARCH AND TECHNOLOGY

cout << "R >= " << Resources(process, need);

return 0;

Output
SAGAR INSTITUTE OF RESEARCH AND TECHNOLOGY

EXPERIMENT 6
AIM: Study of classical inter process communication problem (producer consumer)

Algorithm:

The producer-consumer problem illustrates the need for synchronization in systems where
many processes share a resource. In the problem, two processes share a fixed-size buffer. One
process produces information and puts it in the buffer, while the other process consumes
information from the buffer. These processes do not take turns accessing the buffer, they both
work concurrently. Here in lies the problem. What happens if the producer tries to put an item
into a full buffer? What happens if the consumer tries to take an item from an empty buffer?

In order to synchronize these processes, we will block the producer when the buffer is full,
and we will block the consumer when the buffer is empty. So the two processes, Producer
and Consumer, should work as follows:

(1) The producer must first create a new widget.


(2) Then, it checks to see if the buffer is full. If it is, the producer will put itself to sleep
until the consumer wakes it up. A "wakeup" will come if the consumer finds the
buffer empty.
(3) Next, the producer puts the new widget in the buffer. If the producer goes to sleep in
step (2), it will not wake up until the buffer is empty, so the buffer will never
overflow.
(4) Then, the producer checks to see if the buffer is empty. If it is, the producer assumes
that the consumer is sleeping, an so it will wake the consumer. Keep in mind that
between any of these steps, an interrupt might occur, allowing the consumer to run.
SAGAR INSTITUTE OF RESEARCH AND TECHNOLOGY

(1) The consumer checks to see if the buffer is empty. If so, the consumer will put itself
to sleep until the producer wakes it up. A "wakeup" will occur if the producer finds
the buffer empty after it puts an item into the buffer.
(2) Then, the consumer will remove a widget from the buffer. The consumer will never
try to remove a widget from an empty buffer because it will not wake up until the
buffer is full.
(3) If the buffer was full before it removed the widget, the consumer will wake the
producer.
(4) Finally, the consumer will consume the widget. As was the case with the producer, an
interrupt could occur between any of these steps, allowing the producer to run.

Program: - #include <iostream>


#include <string>
#include <queue>
#include <thread>
#include <mutex>
#include <condition_variable>
#include <chrono>
#include <cstdlib>

const int BUFFER_SIZE = 5;


std::queue<std::string> buffer;

std::mutex mtx;
std::condition_variable buffer_full;
std::condition_variable buffer_empty;

int widget_id = 1;

void producer() {
while (true) {
// Simulate time to produce an item
std::this_thread::sleep_for(std::chrono::milliseconds(rand() % 1000 + 500));
SAGAR INSTITUTE OF RESEARCH AND TECHNOLOGY

std::string item = "Widget-" + std::to_string(widget_id++);

std::unique_lock<std::mutex> lock(mtx);

// Wait if the buffer is full


buffer_full.wait(lock, [] { return buffer.size() < BUFFER_SIZE; });

// Add the item to the buffer


buffer.push(item);
std::cout << "[Producer] Inserted " << item << " into buffer. Buffer size: " << buffer.size()
<< std::endl;

// Notify the consumer that a new item is available


buffer_empty.notify_one();
}
}

void consumer() {
while (true) {
std::unique_lock<std::mutex> lock(mtx);

// Wait if the buffer is empty


buffer_empty.wait(lock, [] { return !buffer.empty(); });

// Remove the item from the buffer


std::string item = buffer.front();
buffer.pop();
std::cout << "[Consumer] Removed " << item << " from buffer. Buffer size: " <<
buffer.size() << std::endl;

// Notify the producer that there is space in the buffer


buffer_full.notify_one();

lock.unlock();

// Simulate time to consume an item


std::this_thread::sleep_for(std::chrono::milliseconds(rand() % 1500 + 500));
std::cout << "[Consumer] Consumed " << item << std::endl;
}
}

int main() {
srand(static_cast<unsigned>(time(nullptr)));

std::thread producer_thread(producer);
std::thread consumer_thread(consumer);
SAGAR INSTITUTE OF RESEARCH AND TECHNOLOGY

producer_thread.join();
consumer_thread.join();

return 0;
}

Output: -
SAGAR INSTITUTE OF RESEARCH AND TECHNOLOGY

EXPERIMENT 7
AIM: Program to implement classical inter process communication problem (Reader Writers).

Problem: -

 There is a shared resource which should be accessed by multiple processes.


 There are two types of processes in this context.
 They are reader and writer.
 Any number of readers can read from the shared resource simultaneously, but only one writer
can write to the shared resource.
 When a writer is writing data to the resource, no other process can access the resource.
 A writer cannot write to the resource if there are non-zero number of readers accessing the
resource at that time.

Solution 1 Using Semaphores :-


Here, readers have higher priority than writer. If a writer wants to write to the resource, it must wait
until there are no readers currently accessing that resource.
Here, we use:-

 one mutex m and a semaphore w.

 An integer variable read_count:- used to maintain the number of readers currently accessing
the resource. The variable read_count is initialized to 0.

 A value of 1 is given initially to m and w.


Instead of having the process to acquire lock on the shared resource, we use the mutex m to
make the process to acquire and release lock whenever it is updating the read_count variable.
a. Writer Process:

1. Writer requests the entry to critical section.

2. If allowed i.e. wait() gives a true value, it enters and performs the write. If not allowed, it
keeps on waiting.

3. It exits the critical section.

while (TRUE)
{
wait(w);
/* perform the write operation */
signal(w);
}
b. Reader Process :
1. Reader requests the entry to critical section.
SAGAR INSTITUTE OF RESEARCH AND TECHNOLOGY

2. If allowed:
i. It increments the count of number of readers inside the critical section. If this reader is the
first reader entering, it locks the w semaphore to restrict the entry of writers if any reader is
inside.
ii. It then, signals mutex as any other reader is allowed to enter while others are already
reading.
iii. After performing reading, it exits the critical section. When exiting, it checks if no more
reader is inside, it signals the semaphore was now, writer can enter the critical section.

3. If not allowed, it keeps on waiting.

while (TRUE)

//acquire lock

wait(m);

read_count++;

if(read_count == 1)

wait(w);

//release lock

signal(m);

/* perform the reading operation */

// acquire lock

wait(m);

read_count--;

if(read_count == 0)

signal(w);

// release lock

signal(m);

Program :-

#include <iostream>
SAGAR INSTITUTE OF RESEARCH AND TECHNOLOGY

#include <pthread.h>

#include <semaphore.h>

#include <unistd.h>

using namespace std;

// Function prototypes

void* reader(void* id);

void* writer(void* id);

// Shared variables

int readcount = 0, writecount = 0;

int sh_var = 5;

// Semaphores

sem_t x, y, z, rsem, wsem;

// Threads

pthread_t r[5], w[2];

void* reader(void* id) {

int reader_id = *((int*)id);

sem_wait(&z);

sem_wait(&rsem);

sem_wait(&x);

readcount++;

if (readcount == 1)

sem_wait(&wsem);
SAGAR INSTITUTE OF RESEARCH AND TECHNOLOGY

sem_post(&x);

sem_post(&rsem);

sem_post(&z);

// Reading section

cout << "\n[Reader " << reader_id << "] Reading value: " << sh_var << endl;

sleep(1);

sem_wait(&x);

readcount--;

if (readcount == 0)

sem_post(&wsem);

sem_post(&x);

return nullptr;

void* writer(void* id) {

int writer_id = *((int*)id);

sem_wait(&y);

writecount++;

if (writecount == 1)

sem_wait(&rsem);

sem_post(&y);

sem_wait(&wsem);

// Writing section
SAGAR INSTITUTE OF RESEARCH AND TECHNOLOGY

cout << "\n[Writer " << writer_id << "] Writing..." << endl;

sh_var += 5;

cout << "[Writer " << writer_id << "] Updated value: " << sh_var << endl;

sleep(1);

sem_post(&wsem);

sem_wait(&y);

writecount--;

if (writecount == 0)

sem_post(&rsem);

sem_post(&y);

return nullptr;

int main() {

// Initialize semaphores

sem_init(&x, 0, 1);

sem_init(&y, 0, 1);

sem_init(&z, 0, 1);

sem_init(&rsem, 0, 1);

sem_init(&wsem, 0, 1);

int r_ids[5] = {0, 1, 2, 3, 4};

int w_ids[2] = {0, 1};

// Create threads

pthread_create(&r[0], nullptr, reader, &r_ids[0]);

pthread_create(&w[0], nullptr, writer, &w_ids[0]);


SAGAR INSTITUTE OF RESEARCH AND TECHNOLOGY

pthread_create(&r[1], nullptr, reader, &r_ids[1]);

pthread_create(&r[2], nullptr, reader, &r_ids[2]);

pthread_create(&r[3], nullptr, reader, &r_ids[3]);

pthread_create(&w[1], nullptr, writer, &w_ids[1]);

pthread_create(&r[4], nullptr, reader, &r_ids[4]);

// Join threads

for (int i = 0; i < 5; i++) pthread_join(r[i], nullptr);

for (int i = 0; i < 2; i++) pthread_join(w[i], nullptr);

// Destroy semaphores

sem_destroy(&x);

sem_destroy(&y);

sem_destroy(&z);

sem_destroy(&rsem);

sem_destroy(&wsem);

return 0;

Output: -
SAGAR INSTITUTE OF RESEARCH AND TECHNOLOGY

EXPERIMENT 8
AIM: Program to implement classical inter process communication problem (Dining Philosophers).

The Dining Philosophers Problem is a classic example of a synchronization problem involving


concurrent access to shared resources (chopsticks/forks) among multiple processes (philosophers).
The scenario involves five philosophers sitting around a circular table, where each philosopher
alternates between thinking and eating. To eat, a philosopher needs both the left and right forks,
which are shared with neighbouring philosophers.

The challenge lies in designing a system that:

 Prevents deadlock (where each philosopher holds one fork and waits indefinitely),

 Avoids starvation (a philosopher waits forever to eat),

 Ensures mutual exclusion (no two philosophers use the same fork at the same time),

 Maintains concurrency (multiple philosophers can eat simultaneously if forks are available).

Algorithm: -

1. Start:

o Create 5 philosopher threads.

o Create 5 semaphores (1 for each fork).

o Use a mutex for controlling access to shared resources.

2. Thinking:

o Philosopher does not need forks.

o Thinks for a while.

3. Get Hungry:

o Philosopher wants to eat.

o Tries to pick up the left and right forks.

4. Try to Pick Up Forks:

o Lock the mutex to avoid race conditions.

o If both forks are free, pick them up and start eating.

o If not, wait.

5. Eating:

o Philosopher eats for some time.


SAGAR INSTITUTE OF RESEARCH AND TECHNOLOGY

6. Put Down Forks:

o Lock the mutex again.

o Put both forks back on the table.

o Allow neighboring philosophers to eat if they are hungry.

7. Repeat:

o Philosopher goes back to thinking and the cycle continues.

Program:

#include <iostream>

#include <pthread.h>

#include <semaphore.h>

#include <unistd.h>

using namespace std;

#define N 5 // Number of philosophers

enum { THINKING, HUNGRY, EATING } state[N];

int phil[N] = {0, 1, 2, 3, 4};

sem_t mutex; // Global mutex for mutual exclusion

sem_t S[N]; // One semaphore per philosopher

void test(int i) {

if (state[i] == HUNGRY &&

state[(i + 4) % N] != EATING &&

state[(i + 1) % N] != EATING) {

state[i] = EATING;
SAGAR INSTITUTE OF RESEARCH AND TECHNOLOGY

sleep(1);

cout << "[Philosopher " << i << "] takes forks " << (i + 4) % N

<< " and " << i << " and starts EATING\n";

sem_post(&S[i]);

void take_forks(int i) {

sem_wait(&mutex);

state[i] = HUNGRY;

cout << "[Philosopher " << i << "] is HUNGRY\n";

test(i);

sem_post(&mutex);

sem_wait(&S[i]);

void put_forks(int i) {

sem_wait(&mutex);

state[i] = THINKING;

cout << "[Philosopher " << i << "] puts down forks and starts THINKING\n";

test((i + 4) % N);

test((i + 1) % N);

sem_post(&mutex);

void* philosopher(void* num) {

int i = *(int*)num;
SAGAR INSTITUTE OF RESEARCH AND TECHNOLOGY

while (true) {

sleep(1);

take_forks(i);

sleep(2);

put_forks(i);

return nullptr;

int main() {

pthread_t thread_id[N];

// Initialize semaphores

sem_init(&mutex, 0, 1);

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

sem_init(&S[i], 0, 0);

// Create philosopher threads

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

pthread_create(&thread_id[i], NULL, philosopher, &phil[i]);

cout << "Philosopher " << i << " is THINKING\n";

// Join threads (infinite loop unless interrupted)

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

pthread_join(thread_id[i], NULL);
SAGAR INSTITUTE OF RESEARCH AND TECHNOLOGY

return 0;

Output: -
SAGAR INSTITUTE OF RESEARCH AND TECHNOLOGY

EXPERIMENT 9
AIM: Program to implement FIFO page replacement algorithm.

ALGORITHM

1. Start the process

2. Declare the size with respect to page length

3. Check the need of replacement from the page to memory

4. Check the need of replacement from old page to new page in memory

5. Forma queue to hold all pages

6. Insert the page require memory into the queue

7. Check for bad replacement and page fault

8. Get the number of processes to be inserted

9. Display the values

10. Stop the process

Program:

#include <iostream>
#include <queue>
#include <unordered_set>
using namespace std;

void fifoPageReplacement(int pages[], int n, int capacity) {


unordered_set<int> memory; // To store pages in memory (unique)
queue<int> indexQueue; // To maintain FIFO order

int pageFaults = 0;

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


int currentPage = pages[i];

// Page is not present in memory (Page Fault)


if (memory.find(currentPage) == memory.end()) {
// If memory is full, remove the oldest page (FIFO)
if (memory.size() == capacity) {
int oldestPage = indexQueue.front();
indexQueue.pop();
memory.erase(oldestPage);
}

// Insert the current page


memory.insert(currentPage);
SAGAR INSTITUTE OF RESEARCH AND TECHNOLOGY

indexQueue.push(currentPage);
pageFaults++;

cout << "Page " << currentPage << " added -> Page Fault!" << endl;
} else {
cout << "Page " << currentPage << " already in memory -> No Page Fault." << endl;
}
}

cout << "\nTotal Page Faults = " << pageFaults << endl;
}

int main() {
int pages[] = {1, 3, 0, 3, 5, 6};
int n = sizeof(pages) / sizeof(pages[0]);
int capacity;

cout << "Enter the number of frames (capacity of memory): ";


cin >> capacity;

fifoPageReplacement(pages, n, capacity);

return 0;
}

Output: -
SAGAR INSTITUTE OF RESEARCH AND TECHNOLOGY

EXPERIMENT 10
AIM: Program to implement LRU page replacement algorithm.

ALGORITHM

1. Start the process

2. Declare the size

3. Get the number of pages to be inserted

4. Get the value

5. Declare counter and stack

6. Select the least recently used page by counter value

7. Stack them according the selection.

8. Display the values

9. Stop the process

Program:

#include <iostream>
#include <list>
#include <unordered_map>
using namespace std;

void lruPageReplacement(int pages[], int n, int capacity) {


list<int> memory; // List to store pages (most recent at front)
unordered_map<int, list<int>::iterator> pageMap; // To quickly find and update page positions

int pageFaults = 0;

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


int currentPage = pages[i];

// Page not present in memory (Page Fault)


if (pageMap.find(currentPage) == pageMap.end()) {
if (memory.size() == capacity) {
int lruPage = memory.back();
memory.pop_back(); // Remove LRU page
pageMap.erase(lruPage);
}

memory.push_front(currentPage); // Add current page to front


pageMap[currentPage] = memory.begin();
pageFaults++;

cout << "Page " << currentPage << " added -> Page Fault!" << endl;
SAGAR INSTITUTE OF RESEARCH AND TECHNOLOGY

} else {
// Page already in memory, move it to front (most recently used)
memory.erase(pageMap[currentPage]);
memory.push_front(currentPage);
pageMap[currentPage] = memory.begin();

cout << "Page " << currentPage << " accessed -> No Page Fault." << endl;
}
}

cout << "\nTotal Page Faults = " << pageFaults << endl;
}

int main() {
int pages[] = {1, 2, 3, 2, 4, 1, 5};
int n = sizeof(pages) / sizeof(pages[0]);
int capacity;

cout << "Enter the number of frames (capacity of memory): ";


cin >> capacity;

lruPageReplacement(pages, n, capacity);

return 0;
}

Output: -

You might also like

pFad - Phonifier reborn

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

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


Alternative Proxies:

Alternative Proxy

pFad Proxy

pFad v3 Proxy

pFad v4 Proxy