0% found this document useful (0 votes)
35 views40 pages

Network Analysis Os

The document contains C code for implementing three CPU scheduling algorithms: first come first serve (FCFS), shortest job first (SJF), and round robin (RR). It includes functions to calculate waiting times, turnaround times, average waiting times and average turnaround times for a given set of processes. For SJF and priority scheduling, it sorts the processes by burst time or priority respectively before performing calculations.

Uploaded by

I'm KING
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)
35 views40 pages

Network Analysis Os

The document contains C code for implementing three CPU scheduling algorithms: first come first serve (FCFS), shortest job first (SJF), and round robin (RR). It includes functions to calculate waiting times, turnaround times, average waiting times and average turnaround times for a given set of processes. For SJF and priority scheduling, it sorts the processes by burst time or priority respectively before performing calculations.

Uploaded by

I'm KING
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/ 40

FFCS

#include <stdio.h>

// Structure to represent a process

typedef struct

int processId;

int arrivalTime;

int burstTime;

} Process;

// Function to calculate the waiting time for each process

void calculateWaitingTime(Process processes[], int n, int waitingTime[])

waitingTime[0] = 0; // Waiting time for the first process is always 0

for (int i = 1; i < n; i++)

waitingTime[i] = waitingTime[i - 1] + processes[i - 1].burstTime;

// Function to calculate the turnaround time for each process

void calculateTurnaroundTime(Process processes[], int n, int waitingTime[], int turnaroundTime[])

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

turnaroundTime[i] = processes[i].burstTime + waitingTime[i];

}
// Function to calculate the average waiting time and average turnaround time

void calculateAverageTimes(Process processes[], int n)

int waitingTime[n], turnaroundTime[n];

int totalWaitingTime = 0, totalTurnaroundTime = 0;

// Calculate waiting time and turnaround time for each process

calculateWaitingTime(processes, n, waitingTime);

calculateTurnaroundTime(processes, n, waitingTime, turnaroundTime);

// Calculate total waiting time and total turnaround time

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

totalWaitingTime += waitingTime[i];

totalTurnaroundTime += turnaroundTime[i];

// Calculate average waiting time and average turnaround time

float averageWaitingTime = (float)totalWaitingTime / n;

float averageTurnaroundTime = (float)totalTurnaroundTime / n;

// Print the average times

printf("Average Waiting Time: %.2f\n", averageWaitingTime);

printf("Average Turnaround Time: %.2f\n", averageTurnaroundTime);

// Print waiting time and turnaround time for each process

printf("\nProcess\t\tWaiting Time\tTurnaround Time\n");

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

printf("%d\t\t%d\t\t%d\n", processes[i].processId, waitingTime[i], turnaroundTime[i]);

}
}

int main()

int n; // Number of processes

printf("Enter the number of processes: ");

scanf("%d", &n);

// Create an array of processes

Process processes[n];

// Input the arrival time and burst time for each process

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

printf("Process %d\n", i + 1);

processes[i].processId = i + 1;

printf("Enter arrival time: ");

scanf("%d", &processes[i].arrivalTime);

printf("Enter burst time: ");

scanf("%d", &processes[i].burstTime);

// Calculate average waiting time and average turnaround time

calculateAverageTimes(processes, n);

return 0;

SJF

#include <stdio.h>
// Structure to represent a process

typedef struct

int processId;

int arrivalTime;

int burstTime;

} Process;

// Function to swap two processes

void swap(Process *a, Process *b)

Process temp = *a;

*a = *b;

*b = temp;

// Function to sort the processes based on burst time (SJF)

void sortProcesses(Process processes[], int n)

for (int i = 0; i < n - 1; i++)

for (int j = 0; j < n - i - 1; j++)

if (processes[j].burstTime > processes[j + 1].burstTime)

swap(&processes[j], &processes[j + 1]);

}
// Function to calculate the waiting time for each process

void calculateWaitingTime(Process processes[], int n, int waitingTime[])

waitingTime[0] = 0; // Waiting time for the first process is always 0

for (int i = 1; i < n; i++)

waitingTime[i] = waitingTime[i - 1] + processes[i - 1].burstTime;

// Function to calculate the turnaround time for each process

void calculateTurnaroundTime(Process processes[], int n, int waitingTime[], int turnaroundTime[])

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

turnaroundTime[i] = processes[i].burstTime + waitingTime[i];

// Function to calculate the average waiting time and average turnaround time

void calculateAverageTimes(Process processes[], int n)

int waitingTime[n], turnaroundTime[n];

int totalWaitingTime = 0, totalTurnaroundTime = 0;

// Sort the processes based on burst time (SJF)

sortProcesses(processes, n);

// Calculate waiting time and turnaround time for each process


calculateWaitingTime(processes, n, waitingTime);

calculateTurnaroundTime(processes, n, waitingTime, turnaroundTime);

// Calculate total waiting time and total turnaround time

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

totalWaitingTime += waitingTime[i];

totalTurnaroundTime += turnaroundTime[i];

// Calculate average waiting time and average turnaround time

float averageWaitingTime = (float)totalWaitingTime / n;

float averageTurnaroundTime = (float)totalTurnaroundTime / n;

// Print the average times

printf("Average Waiting Time: %.2f\n", averageWaitingTime);

printf("Average Turnaround Time: %.2f\n", averageTurnaroundTime);

// Print waiting time and turnaround time for each process

printf("\nProcess\t\tWaiting Time\tTurnaround Time\n");

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

printf("%d\t\t%d\t\t%d\n", processes[i].processId, waitingTime[i], turnaroundTime[i]);

int main()

int n; // Number of processes

printf("Enter the number of processes: ");

scanf("%d", &n);
// Create an array of processes

Process processes[n];

// Input the arrival time and burst time for each process

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

printf("Process %d\n", i + 1);

processes[i].processId = i + 1;

printf("Enter arrival time: ");

scanf("%d", &processes[i].arrivalTime);

printf("Enter burst time: ");

scanf("%d", &processes[i].burstTime);

// Calculate average waiting time and average turnaround time

calculateAverageTimes(processes, n);

return 0;

Round Robin
#include <stdio.h>

struct Process {

int id;

int burst;

int arrival;

int wait;

int complete;
int turnAround;

int remaining;

};

void RR(struct Process p[], int n, int slice) {

int finishing = 0, currentTime = 0, change;

double totWaitTime = 0.0;

double totTurnAroundTime = 0.0;

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

p[i].remaining = p[i].burst;

while (finishing < n) {

change = 0;

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

if (p[i].arrival <= currentTime && p[i].remaining > 0) {

finishing++;

currentTime += p[i].remaining;

p[i].complete = currentTime;

p[i].turnAround = p[i].complete - p[i].arrival;

p[i].wait = p[i].turnAround - p[i].burst;

totWaitTime += p[i].wait;

totTurnAroundTime += p[i].turnAround;

p[i].remaining = 0;

} else {

currentTime += slice;

p[i].remaining -= slice;

change++;

if (change == 0)

currentTime++;

}
printf("Avg Waiting Time: %.2f\n", totWaitTime / n);

#include <stdio.h>

struct Process {

int id;

int burst;

int arrival;

int wait;

int complete;

int turnAround;

int remaining;

};

void RR(struct Process p[], int n, int slice) {

int finishing = 0, currentTime = 0, change;

double totWaitTime = 0.0;

double totTurnAroundTime = 0.0;

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

p[i].remaining = p[i].burst;

while (finishing < n) {

change = 0;

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

if (p[i].arrival <= currentTime && p[i].remaining > 0) {

finishing++;

currentTime += p[i].remaining;

p[i].complete = currentTime;

p[i].turnAround = p[i].complete - p[i].arrival;

p[i].wait = p[i].turnAround - p[i].burst;


totWaitTime += p[i].wait;

totTurnAroundTime += p[i].turnAround;

p[i].remaining = 0;

} else {

currentTime += slice;

p[i].remaining -= slice;

change++;

if (change == 0)

currentTime++;

printf("Avg Waiting Time: %.2f\n", totWaitTime / n);

printf("Avg Turn Around Time: %.2f\n", totTurnAroundTime / n);

printf("\nProcess\t\tWaiting Time\tTurnaround Time\n");

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

printf("%d\t\t%d\t\t%d\n", p[i].id, p[i].wait, p[i].turnAround);

int main() {

int n, slice;

printf("Enter number of processes: ");

scanf("%d", &n);

printf("Enter Quantum Time Slice: ");

scanf("%d", &slice);

struct Process p[50];

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


printf("Enter ID: ");

scanf("%d", &p[i].id);

printf("Enter Arrival Time: ");

scanf("%d", &p[i].arrival);

printf("Enter Burst Time: ");

scanf("%d", &p[i].burst);

RR(p, n, slice);

return 0;

Priority Schedular
#include <stdio.h>

#include <stdlib.h>

struct Process {

int id;

int arrTime;

int burstTime;

int priority;

};

int comparePriority(const void* a, const void* b) {

struct Process* p1 = (struct Process*)a;

struct Process* p2 = (struct Process*)b;

return p1->priority - p2->priority;

void waitingTime(struct Process* processes, int* waitingTimes, int n) {

waitingTimes[0] = 0;

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

waitingTimes[i] = processes[i - 1].burstTime + waitingTimes[i - 1];


}

void turnAroundTime(struct Process* processes, int* waitingTimes, int* tat, int n) {

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

tat[i] = processes[i].burstTime + waitingTimes[i];

void averageTime(struct Process* processes, int n) {

int* waitingTimes = (int*)malloc(sizeof(int) * n);

int* turnAroundTimes = (int*)malloc(sizeof(int) * n);

int* completionTimes = (int*)malloc(sizeof(int) * n);

waitingTime(processes, waitingTimes, n);

turnAroundTime(processes, waitingTimes, turnAroundTimes, n);

int totalWaitingTime = 0;

int totalTurnAroundTime = 0;

printf("Process ID\tArrival Time\tBurst Time\tCompletion Time\tWaiting Time\tTurnaround


Time\n");

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

totalWaitingTime += waitingTimes[i];

totalTurnAroundTime += turnAroundTimes[i];

completionTimes[i] = turnAroundTimes[i] + processes[i].burstTime;

printf("%d\t\t%d\t\t%d\t\t%d\t\t%d\t\t%d\n", processes[i].id, processes[i].arrTime,


processes[i].burstTime,

completionTimes[i], waitingTimes[i], turnAroundTimes[i]);

double averageWaitingTime = (double)totalWaitingTime / n;

double averageTurnaroundTime = (double)totalTurnAroundTime / n;

printf("\nAverage Waiting Time: %.2f\n", averageWaitingTime);

printf("Average Turnaround Time: %.2f\n", averageTurnaroundTime);

free(waitingTimes);

free(turnAroundTimes);

free(completionTimes);
}

int main() {

int n;

printf("Enter the number of processes: ");

scanf("%d", &n);

struct Process* processes = (struct Process*)malloc(sizeof(struct Process) * n);

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

printf("Enter ID for process %d: ", i + 1);

scanf("%d", &processes[i].id);

printf("Enter Arrival Time for process %d: ", i + 1);

scanf("%d", &processes[i].arrTime);

printf("Enter Burst Time for process %d: ", i + 1);

scanf("%d", &processes[i].burstTime);

printf("Enter Priority for process %d: ", i + 1);

scanf("%d", &processes[i].priority);

qsort(processes, n, sizeof(struct Process), comparePriority);

averageTime(processes, n);

free(processes);

return 0;

Bankers algorithm:
#include <stdio.h>

#define MAX_PROCESSES 10

#define MAX_RESOURCES 10

// Function to check if the requested resources can be granted to a process

int canAllocateResources(int available[], int max[][MAX_RESOURCES], int


allocated[][MAX_RESOURCES], int n, int m, int process)
{

int need[MAX_PROCESSES][MAX_RESOURCES];

// Calculate the need matrix

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

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

need[i][j] = max[i][j] - allocated[i][j];

// Check if the requested resources are within the available resources and the process's need

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

if (available[j] < need[process][j])

return 0;

return 1;

// Function to perform resource allocation using the Banker's Algorithm

void allocateResources(int available[], int max[][MAX_RESOURCES], int


allocated[][MAX_RESOURCES], int n, int m)

int work[MAX_RESOURCES];

int finish[MAX_PROCESSES] = {0};

int safeSequence[MAX_PROCESSES];
int count = 0;

// Initialize work with available resources

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

work[i] = available[i];

// Find a safe sequence

while (count < n)

int found = 0;

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

if (finish[i] == 0 && canAllocateResources(work, max, allocated, n, m, i))

// Allocate resources to the process

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

work[j] += allocated[i][j];

finish[i] = 1;

safeSequence[count] = i;

count++;

found = 1;

if (found == 0)
{

break; // No safe sequence found

if (count == n)

printf("Safe Sequence: ");

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

printf("P%d ", safeSequence[i]);

printf("\n");

printf("\nAllocation Matrix:\n");

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

printf("P%d ", i);

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

printf("%d ", allocated[i][j]);

printf("\n");

printf("\nMax Matrix:\n");

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

printf("P%d ", i);

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

{
printf("%d ", max[i][j]);

printf("\n");

printf("\nAvailable Resources:\n");

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

printf("%d ", available[i]);

printf("\n");

else

printf("No Safe Sequence Found.\n");

int main()

int n, m; // Number of processes and resources

int available[MAX_RESOURCES];

int max[MAX_PROCESSES][MAX_RESOURCES];

int allocated[MAX_PROCESSES][MAX_RESOURCES];

printf("Enter the number of processes: ");

scanf("%d", &n);

printf("Enter the number of resources: ");

scanf("%d", &m);

// Input the available resources


printf("Enter the available resources:\n");

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

printf("Resource %d: ", i + 1);

scanf("%d", &available[i]);

// Input the maximum required resources for each process

printf("Enter the maximum required resources for each process:\n");

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

printf("Process %d:\n", i + 1);

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

printf("Resource %d: ", j + 1);

scanf("%d", &max[i][j]);

// Input the allocated resources for each process

printf("Enter the allocated resources for each process:\n");

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

printf("Process %d:\n", i + 1);

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

printf("Resource %d: ", j + 1);

scanf("%d", &allocated[i][j]);

}
// Perform resource allocation using the Banker's Algorithm

allocateResources(available, max, allocated, n, m);

return 0;

Deadlock detection(Wait for graph):


#include <stdio.h>

#include <stdbool.h>

#define MAX_PROCESSES 10

// Function to check if a cycle exists in the wait-for graph using DFS

bool isCycleUtil(int process, bool visited[], bool recursionStack[], int graph[][MAX_PROCESSES], int n)

if (visited[process] == false)

// Mark the current process as visited and add it to the recursion stack

visited[process] = true;

recursionStack[process] = true;

// Recur for all the processes in the wait-for graph

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

if (graph[process][i] == 1)

// If the adjacent process is not visited and there is a cycle in its subtree, return true

if (!visited[i] && isCycleUtil(i, visited, recursionStack, graph, n))

return true;
}

// If the adjacent process is visited and present in the recursion stack, return true

else if (recursionStack[i])

return true;

recursionStack[process] = false; // Remove the process from the recursion stack

return false;

// Function to check if a cycle exists in the wait-for graph

bool isCycle(int graph[][MAX_PROCESSES], int n)

bool visited[MAX_PROCESSES] = { false };

bool recursionStack[MAX_PROCESSES] = { false };

// Check for a cycle in the wait-for graph using DFS

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

if (isCycleUtil(i, visited, recursionStack, graph, n))

return true;

return false;

}
int main()

int n; // Number of processes

printf("Enter the number of processes: ");

scanf("%d", &n);

int graph[MAX_PROCESSES][MAX_PROCESSES];

printf("Enter the wait-for graph:\n");

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

printf("Process %d: ", i + 1);

for (int j = 0; j < n; j++)

scanf("%d", &graph[i][j]);

// Check if a cycle exists in the wait-for graph

if (isCycle(graph, n))

printf("Cycle detected in the wait-for graph.\n");

else

printf("No cycle detected in the wait-for graph.\n");

return 0;

}
Peterson Sol:

#include <stdio.h>

#include <stdbool.h>

#include <stdlib.h>

#include <pthread.h>

#include <unistd.h>

#define NUM_THREADS 2

int i,j;

int turn = 0;

bool flag[NUM_THREADS] = { false };

void* threadFunction(void* arg)

int threadId = *(int*)arg;

// Enter the critical section

flag[threadId] = true;

turn = 1 - threadId;

// Busy wait until it's the current thread's turn

while (flag[1 - threadId] && turn == 1 - threadId);

// Critical section

printf("Thread %d entered the critical section.\n", threadId);

sleep(2); // Simulating some work in the critical section

printf("Thread %d exited the critical section.\n", threadId);


// Exit the critical section

flag[threadId] = false;

pthread_exit(NULL);

int main()

pthread_t threads[NUM_THREADS];

int threadIds[NUM_THREADS];

// Create two threads

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

threadIds[i] = i;

pthread_create(&threads[i], NULL, threadFunction, &threadIds[i]);

// Wait for the threads to finish

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

pthread_join(threads[i], NULL);

return 0;

Bounded Buffer:
#include <stdio.h>
#include <stdlib.h>

#include <pthread.h>

#include <semaphore.h>

#define BUFFER_SIZE 16

sem_t fill;

sem_t empty;

pthread_t producerThread[50], consumerThread[50];

int buffer[BUFFER_SIZE];

int counter;

//pthread_mutex_t mutex;

sem_t mutex;

void init()

sem_init(&mutex,0,1);

//pthread_mutex_init(&mutex,NULL);

sem_init(&fill,1,0);

sem_init(&empty,1,BUFFER_SIZE);

counter=0;

void produce(int item)

buffer[counter++]=item;

int consume()
{

counter--;

return buffer[counter];

void *producer(void *param)

int item;

item=rand()%5;

sem_wait(&empty);

/*printf("sem_wait = %d\n",wait );

int val;

printf("emptyb=%d\n", sem_getvalue(&empty,&val));

printf("%d\n",val );

printf("emptya=%d\n", sem_getvalue(&empty,&val));

printf("%d\n",val );*/

//pthread_mutex_lock(&mutex);

sem_wait(&mutex);

printf("Produced item: %d\n", item);

produce(item);

//pthread_mutex_unlock(&mutex);

sem_post(&mutex);

sem_post(&fill);

void *consumer(void *param)

int item;

sem_wait(&fill);

//pthread_mutex_lock(&mutex);
sem_wait(&mutex);

item =consume();

printf("Consumed item: %d\n",item );

sem_post(&mutex);

//pthread_mutex_unlock(&mutex);

sem_post(&fill);

int main()

int i,number_of_producers,number_of_consumers;

init();

printf("Enter number of producers: ");

scanf("%d",&number_of_producers);

printf("Enter number of consumers: ");

scanf("%d",&number_of_consumers);

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

pthread_create(&producerThread[i],NULL,producer,NULL);

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

pthread_create(&consumerThread[i],NULL,consumer,NULL);

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

pthread_join(producerThread[i],NULL);
}

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

pthread_join(consumerThread[i],NULL);

return 0;

Best Fit Memory Allocation Algorithm

#include <stdio.h>

void main()

int fragment[20], b[20], p[20], i, j, nb, np, temp, lowest = 9999;

static int barray[20], parray[20];

printf("Enter the number of blocks:");

scanf("%d", &nb);

printf("Enter the number of processes:");

scanf("%d", &np);

printf("\nEnter the size of the blocks:-\n");

for (i = 1; i <= nb; i++)

printf("Block no.%d:", i);

scanf("%d", &b[i]);

printf("\nEnter the size of the processes :-\n");

for (i = 1; i <= np; i++)

printf("Process no.%d:", i);

scanf("%d", &p[i]);
}

for (i = 1; i <= np; i++)

for (j = 1; j <= nb; j++)

if (barray[j] != 1)

temp = b[j] - p[i];

if (temp >= 0)

if (lowest > temp)

parray[i] = j;

lowest = temp;

fragment[i] = lowest;

barray[parray[i]] = 1;

lowest = 10000;

printf("\nProcess_no\tProcess_size\tBlock_no\tBlock_size\tFragment");

for (i = 1; i <= np && parray[i] != 0; i++)

printf("\n%d\t\t%d\t\t%d\t\t%d\t\t%d", i, p[i], parray[i], b[parray[i]],

fragment[i]);

Worst Fit Memory Allocation Algorithm:


#include <stdio.h>

int main()

{
int n, n1, i;

printf("enter the number of processes:");

scanf("%d", &n);

int process[n];

printf("\n enter the size of processes:\n");

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

scanf("%d", &process[i]);

printf("enter the no of memoryblocks:");

scanf("%d", &n1);

int blocks[n1];

printf("\n enter the size of blocks:\n");

int total = 0;

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

scanf("%d", &blocks[i]);

total = total + blocks[i];

int process1[n1];

int job[n1];

int frag[n1];

int check[n1];

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

check[i] = 0;

int j, used = 0;

i = 0;

while (i < n)

{
int max = -1, j1 = -1, k = -1, max1;

for (j = 0; j < n1; j++)

max1 = blocks[j];

if (max1 >= max && check[j] == 0 && max1 >= process[i])

max = max1;

j1 = j;

else

if (check[j] == 0)

process1[j] = 0;

job[j] = 0;

frag[j] = blocks[j];

if (k != j1)

process1[j1] = process[i];

job[j1] = i + 1;

frag[j1] = blocks[j1] - process[i];

used = used + process[i];

check[j1] = 1;

int l;

i++;

printf("blocksize\tprocess size\tprocessno\tfragmentation\n");
for (i = 0; i < n1; i++)

printf("%d\t\t%d\t\t%d\t\t%d\n", blocks[i], process1[i], job[i], frag[i]);

printf("totalmemoryallocation:%d\n", total);

printf("memoryused:%d\n", used);

First Fit Memory Allocation Algorithm:

#include<stdio.h>

void main()

int bsize[10], psize[10], bno, pno, flags[10], allocation[10], i, j;

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

flags[i] = 0;

allocation[i] = -1;

printf("Enter no. of blocks: ");

scanf("%d", &bno);

printf("\nEnter size of each block: ");

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

scanf("%d", &bsize[i]);

printf("\nEnter no. of processes: ");

scanf("%d", &pno);

printf("\nEnter size of each process: ")

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

scanf("%d", &psize[i]);

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


for(j = 0; j < bno; j++)

if(flags[j] == 0 && bsize[j] >= psize[i])

allocation[j] = i;

flags[j] = 1;

break;

printf("\nBlock no.\tsize\t\tprocess no.\t\tsize");

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

printf("\n%d\t\t%d\t\t", i+1, bsize[i]);

if(flags[i] == 1)

printf("%d\t\t\t%d",allocation[i]+1,psize[allocation[i]]);

else

printf("Not allocated");

FIFO Page Replacement Algorithm:


#include<stdio.h>

int i,j;

int main()

int numFrames, numPages;

int frames[10], pages[30];

int faults = 0, frameIndex = 0;

printf("Enter the number of frames: ");

scanf("%d", &numFrames);
printf("Enter the number of pages: ");

scanf("%d", &numPages);

printf("Enter the page reference string: ");

for ( i = 0; i < numPages; ++i) {

scanf("%d", &pages[i]);

// Initialize frames with -1 to indicate empty frames

for ( i = 0; i < numFrames; ++i) {

frames[i] = -1;

for ( i = 0; i < numPages; ++i) {

int page = pages[i];

int pageFound = 0;

// Check if the page is already in a frame

for ( j = 0; j < numFrames; ++j) {

if (frames[j] == page) {

pageFound = 1;

break;

// If the page is not found in any frame, it's a page fault

if (pageFound == 0) {

frames[frameIndex] = page;

frameIndex = (frameIndex + 1) % numFrames;

faults++;
}

printf("\n");

for ( j = 0; j < numFrames; ++j) {

printf("%d\t", frames[j]);

printf("\n\nTotal Page Faults = %d", faults);

return 0;

Lru
#include<stdio.h>

int findLRU(int time[], int n){

int i, minimum = time[0], pos = 0;

for(i = 1; i < n; ++i){

if(time[i] < minimum){

minimum = time[i];

pos = i;

return pos;

int main()

int no_of_frames, no_of_pages, frames[10], pages[30], counter = 0,

time[10], flag1, flag2, i, j, pos, faults = 0;

printf("Enter number of frames: ");

scanf("%d", &no_of_frames);
printf("Enter number of pages: ");

scanf("%d", &no_of_pages);

printf("Enter reference string: ");

for(i = 0; i < no_of_pages; ++i){

scanf("%d", &pages[i]);

for(i = 0; i < no_of_frames; ++i){

frames[i] = -1;

for(i = 0; i < no_of_pages; ++i){

flag1 = flag2 = 0;

for(j = 0; j < no_of_frames; ++j){

if(frames[j] == pages[i]){

counter++;

time[j] = counter;

flag1 = flag2 = 1;

break;

if(flag1 == 0){

for(j = 0; j < no_of_frames; ++j){

if(frames[j] == -1){

counter++;

faults++;

frames[j] = pages[i];

time[j] = counter;

flag2 = 1;

break;

}
if(flag2 == 0){

pos = findLRU(time, no_of_frames);

counter++;

faults++;

frames[pos] = pages[i];

time[pos] = counter;

printf("\n");

for(j = 0; j < no_of_frames; ++j){

printf("%d\t", frames[j]);

printf("\n\nTotal Page Faults = %d", faults);

return 0;

Optimal page replacement:


#include<stdio.h>

int main()

int no_of_frames, no_of_pages, frames[10], pages[30], temp[10], flag1,

flag2, flag3, i, j, k, pos, max, faults = 0;

printf("Enter number of frames: ");

scanf("%d", &no_of_frames);

printf("Enter number of pages: ");

scanf("%d", &no_of_pages);

printf("Enter page reference string: ");

for(i = 0; i < no_of_pages; ++i){

scanf("%d", &pages[i]);

}
for(i = 0; i < no_of_frames; ++i){

frames[i] = -1;

for(i = 0; i < no_of_pages; ++i){

flag1 = flag2 = 0;

for(j = 0; j < no_of_frames; ++j){

if(frames[j] == pages[i]){

flag1 = flag2 = 1;

break;

if(flag1 == 0){

for(j = 0; j < no_of_frames; ++j){

if(frames[j] == -1){

faults++;

frames[j] = pages[i];

flag2 = 1;

break;

if(flag2 == 0){

flag3 =0;

for(j = 0; j < no_of_frames; ++j){

temp[j] = -1;

for(k = i + 1; k < no_of_pages; ++k){

if(frames[j] == pages[k]){

temp[j] = k;

break;

}
}

for(j = 0; j < no_of_frames; ++j){

if(temp[j] == -1){

pos = j;

flag3 = 1;

break;

if(flag3 ==0){

max = temp[0];

pos = 0;

for(j = 1; j< no_of_frames; ++j){

if(temp[j] > max){

max = temp[j];

pos = j;

frames[pos] = pages[i];

faults++;

printf("\n");

for(j = 0; j < no_of_frames; ++j){

printf("%d\t", frames[j]);

printf("\n\nTotal Page Faults = %d", faults);

return 0;

}
Thread:

#include <stdio.h>

#include <stdlib.h>

#include <unistd.h>

#include <pthread.h>

// Let us create a global variable to change it in threads

int g = 0;

// The function to be executed by all threads

void *myThreadFun(void *vargp)

// Store the value argument passed to this thread

int *myid = (int *)vargp;

// Let us create a static variable to observe its changes

static int s = 0;

// Change static and global variables

++s; ++g;

// Print the argument, static and global variables

printf("Thread ID: %d, Static: %d, Global: %d\n", *myid, ++s, ++g);

int main()

int i;

pthread_t tid;

// Let us create three threads

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

pthread_create(&tid, NULL, myThreadFun, (void *)&tid);

pthread_exit(NULL);

return 0;

You might also like