Operating System Lab Report

Download as pdf or txt
Download as pdf or txt
You are on page 1of 27

1

Experiment No: 1
Experiment Name: First-Come, First-Served (FCFS) Scheduling.

Code (In C):


#include <stdio.h>

int main()

int pid[15];

int bt[15];

int n;

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

scanf("%d",&n);

printf("Enter process id of all the processes: ");

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

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

printf("Enter burst time of all the processes: ");

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

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

}
2

int i, wt[n];

wt[0]=0;

//for calculating waiting time of each process

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

wt[i]= bt[i-1]+ wt[i-1];

printf("Process ID Burst Time Waiting Time TurnAround Time\n");

float twt=0.0;

float tat= 0.0;

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

printf("%d\t\t", pid[i]);

printf("%d\t\t", bt[i]);

printf("%d\t\t", wt[i]);

//calculating and printing turnaround time of each process

printf("%d\t\t", bt[i]+wt[i]);

printf("\n");

//for calculating total waiting time


3

twt += wt[i];

//for calculating total turnaround time

tat += (wt[i]+bt[i]);

float att,awt;

//for calculating average waiting time

awt = twt/n;

//for calculating average turnaround time

att = tat/n;

printf("Avg. waiting time= %f\n",awt);

printf("Avg. turnaround time= %f",att);

Input:

Output:
4

Experiment No: 2
Experiment Name: Shortest Job First Scheduling.

Code (In C):


#include<stdio.h>
int main()
{
int bt[20],p[20],wt[20],tat[20],i,j,n,total=0,totalT=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;
}

//sorting of burst times


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;

//finding the waiting time of all the processes


for(i=1;i<n;i++)
{
wt[i]=0;
for(j=0;j<i;j++)
//individual WT by adding BT of all previous completed processes
wt[i]+=bt[j];
5

//total waiting time


total+=wt[i];
}

//average waiting time


avg_wt=(float)total/n;

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


for(i=0;i<n;i++)
{
//turnaround time of individual processes
tat[i]=bt[i]+wt[i];

//total turnaround time


totalT+=tat[i];
printf("\np%d\t\t %d\t\t %d\t\t\t%d",p[i],bt[i],wt[i],tat[i]);
}
//average turnaround time
avg_tat=(float)totalT/n;
printf("\n\nAverage Waiting Time=%f",avg_wt);
printf("\nAverage Turnaround Time=%f\n",avg_tat);
}

Input:

Output:
6

Experiment No.: 3
Experiment Name: Priority Scheduling.

Code (In C):


#include <stdio.h>
//Function to swap two variables
void swap(int *a,int *b)
{
int temp=*a;
*a=*b;
*b=temp;
}
int main()
{
int n;
printf("Enter Number of Processes: ");
scanf("%d",&n);

// b is array for burst time, p for priority and index for process id
int b[n],p[n],index[n];
for(int i=0;i<n;i++)
{
printf("Enter Burst Time and Priority Value for Process %d: ",i+1);
scanf("%d %d",&b[i],&p[i]);
index[i]=i+1;
}
for(int i=0;i<n;i++)
{
int a=p[i],m=i;

//Finding out highest priority element and placing it at its desired position
for(int j=i;j<n;j++)
{
if(p[j] > a)
{
a=p[j];
m=j;
}
}

//Swapping processes
swap(&p[i], &p[m]);
swap(&b[i], &b[m]);
7

swap(&index[i],&index[m]);
}

// T stores the starting time of process


int t=0;

//Printing scheduled process


printf("Order of process Execution is\n");
for(int i=0;i<n;i++)
{
printf("P%d is executed from %d to %d\n",index[i],t,t+b[i]);
t+=b[i];
}
printf("\n");
printf("Process Id Burst Time Wait Time TurnAround Time\n");
int wait_time=0;
for(int i=0;i<n;i++)
{
printf("P%d %d %d %d\n",index[i],b[i],wait_time,wait_time + b[i]);
wait_time += b[i];
}
return 0;
}

Input:

Output:
8

Experiment No.: 4
Experiment Name: Round Robin Scheduling.

Code (In C):


#include<stdio.h>

int main()
{
//Input no of processed
int n;
printf("Enter Total Number of Processes:");
scanf("%d", &n);
int wait_time = 0, ta_time = 0, arr_time[n], burst_time[n], temp_burst_time[n];
int x = n;

//Input details of processes


for(int i = 0; i < n; i++)
{
printf("Enter Details of Process %d \n", i + 1);
printf("Arrival Time: ");
scanf("%d", &arr_time[i]);
printf("Burst Time: ");
scanf("%d", &burst_time[i]);
temp_burst_time[i] = burst_time[i];
}

//Input time slot


int time_slot;
printf("Enter Time Slot:");
scanf("%d", &time_slot);

//Total indicates total time


//counter indicates which process is executed
int total = 0, counter = 0,i;
printf("Process ID Burst Time Turnaround Time Waiting Time\n");
for(total=0, i = 0; x!=0; )
{
// define the conditions
if(temp_burst_time[i] <= time_slot && temp_burst_time[i] > 0)
{
total = total + temp_burst_time[i];
temp_burst_time[i] = 0;
counter=1;
9

}
else if(temp_burst_time[i] > 0)
{
temp_burst_time[i] = temp_burst_time[i] - time_slot;
total += time_slot;
}
if(temp_burst_time[i]==0 && counter==1)
{
x--; //decrement the process no.
printf("\nProcess No %d \t\t %d\t\t\t\t %d\t\t\t %d", i+1, burst_time[i],
total-arr_time[i], total-arr_time[i]-burst_time[i]);
wait_time = wait_time+total-arr_time[i]-burst_time[i];
ta_time += total -arr_time[i];
counter =0;
}
if(i==n-1)
{
i=0;
}
else if(arr_time[i+1]<=total)
{
i++;
}
else
{
i=0;
}
}
float average_wait_time = wait_time * 1.0 / n;
float average_turnaround_time = ta_time * 1.0 / n;
printf("\nAverage Waiting Time:%f", average_wait_time);
printf("\nAvg Turnaround Time:%f\n", average_turnaround_time);
return 0;
}
10

Input:

Output:
11

Experiment No.: 5
Experiment Name: Producer/Consumer Problem.

Code (In C):


// C program for the above approach
#include <stdio.h>
#include <stdlib.h>

// Initialize a mutex to 1
int mutex = 1;

// Number of full slots as 0


int full = 0;

// Number of empty slots as size


// of buffer
int empty = 10, x = 0;

// Function to produce an item and


// add it to the buffer
void producer()
{
// Decrease mutex value by 1
--mutex;

// Increase the number of full


// slots by 1
++full;

// Decrease the number of empty


// slots by 1
--empty;

// Item produced
x++;
printf("\nProducer produces"
"item %d",
x);

// Increase mutex value by 1


++mutex;
}
12

// Function to consume an item and


// remove it from buffer
void consumer()
{
// Decrease mutex value by 1
--mutex;

// Decrease the number of full


// slots by 1
--full;

// Increase the number of empty


// slots by 1
++empty;
printf("\nConsumer consumes "
"item %d",
x);
x--;

// Increase mutex value by 1


++mutex;
}

// Driver Code
int main()
{
int n, i;
printf("\n1. Press 1 for Producer"
"\n2. Press 2 for Consumer"
"\n3. Press 3 for Exit");

// Using '#pragma omp parallel for'


// can give wrong value due to
// synchronization issues.

// 'critical' specifies that code is


// executed by only one thread at a
// time i.e., only one thread enters
// the critical section at a given time
#pragma omp critical

for (i = 1; i > 0; i++) {


13

printf("\nEnter your choice:");


scanf("%d", &n);

// Switch Cases
switch (n) {
case 1:

// If mutex is 1 and empty


// is non-zero, then it is
// possible to produce
if ((mutex == 1)
&& (empty != 0)) {
producer();
}

// Otherwise, print buffer


// is full
else {
printf("Buffer is full!");
}
break;

case 2:

// If mutex is 1 and full


// is non-zero, then it is
// possible to consume
if ((mutex == 1)
&& (full != 0)) {
consumer();
}

// Otherwise, print Buffer


// is empty
else {
printf("Buffer is empty!");
}
break;

// Exit Condition
case 3:
exit(0);
break;
14

}
}
}

Input & Output:


15

Experiment No.: 6
Experiment Name: Bounded Buffer Problem.

Code (In C):


// C program for the above approach
#include <stdio.h>
#include <stdlib.h>

// Initialize a mutex to 1
int mutex = 1;

// Number of full slots as 0


int full = 0;

// Number of empty slots as size


// of buffer
int empty = 10, x = 0;

// Function to produce an item and


// add it to the buffer
void producer()
{
// Decrease mutex value by 1
--mutex;

// Increase the number of full


// slots by 1
++full;

// Decrease the number of empty


// slots by 1
--empty;

// Item produced
x++;
printf("\nProducer produces"
"item %d",
x);

// Increase mutex value by 1


++mutex;
}
16

// Function to consume an item and


// remove it from buffer
void consumer()
{
// Decrease mutex value by 1
--mutex;

// Decrease the number of full


// slots by 1
--full;

// Increase the number of empty


// slots by 1
++empty;
printf("\nConsumer consumes "
"item %d",
x);
x--;

// Increase mutex value by 1


++mutex;
}

// Driver Code
int main()
{
int n, i;
printf("\n1. Press 1 for Producer"
"\n2. Press 2 for Consumer"
"\n3. Press 3 for Exit");

// Using '#pragma omp parallel for'


// can give wrong value due to
// synchronization issues.

// 'critical' specifies that code is


// executed by only one thread at a
// time i.e., only one thread enters
// the critical section at a given time
#pragma omp critical

for (i = 1; i > 0; i++) {


17

printf("\nEnter your choice:");


scanf("%d", &n);

// Switch Cases
switch (n) {
case 1:

// If mutex is 1 and empty


// is non-zero, then it is
// possible to produce
if ((mutex == 1)
&& (empty != 0)) {
producer();
}

// Otherwise, print buffer


// is full
else {
printf("Buffer is full!");
}
break;

case 2:

// If mutex is 1 and full


// is non-zero, then it is
// possible to consume
if ((mutex == 1)
&& (full != 0)) {
consumer();
}

// Otherwise, print Buffer


// is empty
else {
printf("Buffer is empty!");
}
break;

// Exit Condition
case 3:
exit(0);
break;
18

}
}
}

Input & Output:


19

Experiment No.: 7
Experiment Name: Readers and Writer Problem.

Code (In C):


#include <pthread.h>
#include <semaphore.h>
#include <stdio.h>

sem_t wrt;
pthread_mutex_t mutex;
int cnt = 1;
int numreader = 0;

void *writer(void *wno)


{
sem_wait(&wrt);
cnt = cnt*2;
printf("Writer %d modified cnt to %d\n", (*((int *)wno)), cnt);
sem_post(&wrt);
}

void *reader(void *rno)


{
// Reader acquire the lock before modifying numreader
pthread_mutex_lock(&mutex);
numreader++;
if(numreader == 1) {
sem_wait(&wrt); // If this id the first reader, then it will block the writer
}
pthread_mutex_unlock(&mutex);
// Reading Section
printf("Reader %d: read cnt as %d\n", *((int *)rno), cnt);

// Reader acquire the lock before modifying numreader


pthread_mutex_lock(&mutex);
numreader--;
if(numreader == 0) {
sem_post(&wrt); // If this is the last reader, it will wake up the writer.
}
pthread_mutex_unlock(&mutex);
}

int main()
{
int num_readers, num_writers;
20

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


scanf("%d", &num_readers);

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


scanf("%d", &num_writers);

pthread_t read[num_readers], write[num_writers];


pthread_mutex_init(&mutex, NULL);
sem_init(&wrt, 0, 1);

int reader_ids[num_readers];
for(int i = 0; i < num_readers; i++) {
reader_ids[i] = i + 1;
pthread_create(&read[i], NULL, (void *)reader, (void *)&reader_ids[i]);
}
int writer_ids[num_writers];
for(int i = 0; i < num_writers; i++) {
writer_ids[i] = i + 1;
pthread_create(&write[i], NULL, (void *)writer, (void *)&writer_ids[i]);
}

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


pthread_join(read[i], NULL);
}
for(int i = 0; i < num_writers; i++) {
pthread_join(write[i], NULL);
}
pthread_mutex_destroy(&mutex);
sem_destroy(&wrt);

return 0;
}

Input:

Output:
21

Experimpent No.: 8
Exaperiment Name: Dining philosopher problem.

Code (In C):


#include <pthread.h>
#include <semaphore.h>
#include <stdio.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 that eating
state[phnum] = EATING;

sleep(2);

printf("Philosopher %d takes fork %d and %d\n",


phnum + 1, LEFT + 1, phnum + 1);

printf("Philosopher %d is Eating\n", phnum + 1);

// sem_post(&S[phnum]) has no effect


// during takefork
// used to wake up hungry philosophers
// during putfork
sem_post(&S[phnum]);
}
}
22

// take up chopsticks
void take_fork(int phnum)
{

sem_wait(&mutex);

// state that hungry


state[phnum] = HUNGRY;

printf("Philosopher %d is Hungry\n", phnum + 1);

// eat if neighbours are not eating


test(phnum);

sem_post(&mutex);

// if unable to eat wait to be signalled


sem_wait(&S[phnum]);

sleep(1);
}

// put down chopsticks


void put_fork(int phnum)
{

sem_wait(&mutex);

// state that thinking


state[phnum] = THINKING;

printf("Philosopher %d putting fork %d and %d down\n",


phnum + 1, LEFT + 1, phnum + 1);
printf("Philosopher %d is thinking\n", phnum + 1);

test(LEFT);
test(RIGHT);

sem_post(&mutex);
}

void* philosopher(void* num)


23

while (1) {

int* i = num;

sleep(1);

take_fork(*i);

sleep(0);

put_fork(*i);
}
}

int main()
{

int i;
pthread_t thread_id[N];

// initialize the semaphores


sem_init(&mutex, 0, 1);

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

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

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

// create philosopher processes


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

printf("Philosopher %d is thinking\n", i + 1);


}

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

pthread_join(thread_id[i], NULL);
}
24

Output:
25

Experiment No.: 9
Experiment Name: Sleeping Barber Problem.

Code (In C):


#include <stdio.h>
#include <pthread.h>
#include <semaphore.h>
#include <unistd.h>

#define N 5 // Number of chairs in the waiting room

sem_t customers;
sem_t barber;
pthread_mutex_t seats_mutex;
int free_seats = N;

void *barber_thread(void *arg) {


while (1) {
// Wait for customer to arrive
sem_wait(&customers);

// Acquire lock on seats


pthread_mutex_lock(&seats_mutex);

// A chair gets free


free_seats++;

// Wake up the barber


sem_post(&barber);

// Release lock on seats


pthread_mutex_unlock(&seats_mutex);

// Barber is cutting hair


printf("Barber is cutting hair.\n");
sleep(2); // Simulate haircut time
}
return NULL;
}

void *customer_thread(void *arg) {


while (1) {
// Acquire lock on seats
26

pthread_mutex_lock(&seats_mutex);

if (free_seats > 0) {
// Sit down on a chair
free_seats--;

// Notify the barber


sem_post(&customers);

// Release the lock


pthread_mutex_unlock(&seats_mutex);

// Wait for the barber


sem_wait(&barber);

// Customer is having haircut


printf("Customer is having haircut.\n");
sleep(1); // Simulate haircut time
} else {
// Release the lock
pthread_mutex_unlock(&seats_mutex);

// Customer leaves as no free seats available


printf("Customer leaves as no free seats available.\n");
sleep(1); // Simulate leaving time
}
}
return NULL;
}

int main() {
pthread_t barber_tid, customer_tid;

// Initialize semaphores and mutex


sem_init(&customers, 0, 0);
sem_init(&barber, 0, 0);
pthread_mutex_init(&seats_mutex, NULL);

// Create barber thread


pthread_create(&barber_tid, NULL, barber_thread, NULL);

// Create customer threads


pthread_create(&customer_tid, NULL, customer_thread, NULL);
27

pthread_join(barber_tid, NULL);
pthread_join(customer_tid, NULL);

// Destroy semaphores and mutex


sem_destroy(&customers);
sem_destroy(&barber);
pthread_mutex_destroy(&seats_mutex);

return 0;
}

Output:

You might also like