0% found this document useful (0 votes)
29 views21 pages

Os 3

The document discusses implementing a worst fit memory allocation algorithm, where processes are allocated to the largest available memory block, potentially leading to increased fragmentation. It describes how the algorithm searches all memory blocks to find the largest one that can accommodate each process. Pseudocode is provided showing how the algorithm tracks allocated blocks, finds the largest suitable block for each process, and updates the block and allocation status.

Uploaded by

Pragya
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)
29 views21 pages

Os 3

The document discusses implementing a worst fit memory allocation algorithm, where processes are allocated to the largest available memory block, potentially leading to increased fragmentation. It describes how the algorithm searches all memory blocks to find the largest one that can accommodate each process. Pseudocode is provided showing how the algorithm tracks allocated blocks, finds the largest suitable block for each process, and updates the block and allocation status.

Uploaded by

Pragya
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/ 21

OUTPUT: -

[ec2-user@ip-172-31-23-10-)$ vigccfirstfit.c
[[ec2-userl
ec2-userCipip-172-31-23-10
Bnter no. of -blocks:3
172-31-23-10-1$ 1$ /Ef firstfit.c-o fi
Enter size of each blocks 12

Enter no 0f
Enter size
processes:3
of each
4
process:
Block no. size
2 12 Process no
size
2 7S
Not allocated [ec2Userci231T23-l0
AIM: -Implementation of BEST FIT
EXPERIMENT-11
algorithm for memory management.
THEORY: -
Best-Fit Allocation is a memory allocation
to a process. In
Best-Fit, the technigueused in onerating systems to allocate memory
to find the block that is operating system searches through the list of free blocks of memory
closest in size to the memory reguest from
block is found, the theprocess. Once a suitabie
to the process, and operating system splits the block into two parts: the
the remaining free
block. portion that Will be alocated
Advantages of
smallest block of Best-Fit Allocation include improved memory utilization, as it allocates the
memory that is sufficient to
Additionally, Best-Fit can also
blocks of memory that are less help to accommodate the memory request from the process.
reduce memory fragmentation, as it tends to allocate smaller
likely to become
Disadvantages of fragmented.
the best-fit block Best-Fit Allocation
of memory can be include increased computational overhead, as the
algorithm. Additionally, Best-Fit may alsotime-consuming and requires a more search for
smaller blocks of memory result in increased complex search
Overall,
scattered throughout the memory
space.fragmentation, as it may leave
but its Best-Fit Allocation is a widely used memory
effectiveness may vary depending on the specifics
executed. allocation
of the technique operating
in
systems,
system and the workload
being
CODE: -

#include<stdio.h>
void main()

int fragment[20],b[20].p[20],ij,nb,np,temp,lowest-9999;
static int barray[20],parray[201;
printf("\n\t\t\tMemory Management Scheme - Best Fit"):
printf("\nEnter number of blocks:"):
thc
scanf("%d",&nb);
printf("Enter thenumber gfprocesses:");
scanf("od",&np);
printf("\nEnter the size of the blocks:-\n"):
for(i=1;i<=nb;it+)

printf("Block no.%d:",):
scanf("%d",&b[i]D;
}
printf("\nEnter the size of the processes :-\n");
for(i=1;i<-np;it+)
{
printf("Process no.%d:",);
scanf("%od",&p[il);

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

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

if(barrayi]!=1)

temp-b[jil-p[i]:
if(temp>-0)
if(lowest>temp)

parray[i]-j:
lowesttemp;

fragment[i]=lowest:
barray[parfay[i]]=l;
lowest=10000;

printf("\nProcess_no\tProcess_size\tB lock noltBlock_ size\tFragment");


for(i=1;i<=np && parray[i]!=0;it-+)
printf("\n%d\t\t%dltit%d\t\t%dltt%d",i,p[il.parray[i],b[parray[i]],fragment[1);

OUTPUT: -

[ec2-user@ip-172-31-23-10 -1$ vi bestfit.c


[ec2-user@ip-l72-31-23-10-]S gcc bestfit.c-o bf
[ec2-user@ip-172-31-23-10 ~]^ /bf
Memory Mànagement Schema Best Fir
Enter the number of blocks:5
Enter the number of procesSesi4

Enter the size of the blocks


Blocks no1:10
Blocks no.2:15
Blocks no 3:5
Blocks no4:9
Blocks no 5:3

thesize of theaprocesses
Ente
Process no
PrOcess no2:4S
ProCess no.3:7
Blocksize ragmentL
PrOcess size Block no
Process no
1
1 2 [ec2-user@ip-172-31-2310 1
EXPERIMENT -12
AIM: Implementation of WORST FIT algorithm for memory management.
THEORY:
In this allocation technique, the process traverses the whole memory and always search Tor tne
largest hole/partition, and then the process is nlaced in that hole/partition. It is a slow proeess
because it has to traverse the entire memory to search the largest hole.
Here is an example to understand Worst Fit-Allocation

Process Number Process Size


P1 30K
P2 100K
P3 45K

PROCESSSTATUS INTERNAL
MEMORY MEMORY PROCESS
SIZE
FRAGMENTATION
LOCALN BLOCK SZE NUMBER
45K Busy 5K
12345 50K P3
Busy None
P2 100K
45871 100K
30K Busy 370K
400K P1
1245
175K 375K
550K TOTAL
TOTAL
USED:
AVAILABLE:

Fit-Allocation technique, so it trayerses the entire


allocated with the WN orst internal
Here Process P]=30K is is the largest, and hence there is an
memory size 400K which other processes can also utilize this
memory and selects which is very large and so many
fragmentation of 37OK
leftover spacc.
Advantage: largest hole/partitjon, therefore there will be large internal
process chooses the fragmentation will be quite big so that other small processes can
Since this internal
fragmentation. Now, this partition.
placed in that leftover
also be
all the partitions
in the memory and then selects the largest
Disadvantage: traverses time-consuming process.
because it a
is a slow
process partitions, which is
It all the
partition among
CODE: -
#include <stdio.h>

void impliment WorstFit(int blockSize[], int blocks, int processSize(], int processes)

||This will store the block id of the allocated block to a


process
int allocation[processes];
int occupied[blocks);
Il initially assigning -l toall allocation indexes
llmeans nothing is allocated currently
for(int i =0; i< processes; it+){
allocation[i] =-1;

for(int i= 0; i< blocks; it+){


occupied[)=0;

blocks
l/pick each process and find suitable
llaccording to its size ad assign to it
for (int i-0; i< processes; it+)

int indexPlaced = -1;

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

Il if not occupied and block


size is large enough
loccupied[il)
if(blockSize[j]>= processSize[i] &&

process
block fit to accomodate
1/ptáce it at the first
-1)
if (indexPlaccd==
indexPlaccd =:
/ if any future block is larger than the current block where
l process is placed, change the block and thus indexPlaced
clse if (blockSize[indexPlaced] < blockSize[j])
indexPlaccd = j;

/ If we were successfully able to find block for the process


if (indexPlaccd != -1)

l allocate this block j to process p[i]


allocation[i]= indexPlaced;
|/ make the status of the block as occupied
occupied[indexPlaced] = 1:
/ Reduce available menory for the block
blockSize[indexPlaccd] -= processSize[i];

Size\tBlock no.\n");
printf("\nProcess No.\tProcess
processes; it+)
for (int i= 0; i<

i+1, processSize[i):
printf("%d \tltlt %d \t\t\t",
if (allocation[i]!= -1)
printf("%d\n",allocation[i] + );

clsc
printf("Not Allocatcd\n"):
1/Driver code

int main()

int blockSize[] = {100, 50, 30, 120, 35};


int processSize[]= {40, 10, 30, 60};
int blocks =
sizeof(blockSize)/sizeof(blockSize[0]);
int processes =
sizeof(processSize)/sizeof(processSize[0]);
implimentWorstFit(blockSize, blocks, processSize, processes);
return 0:

OUTPUT:-

[ec2-user@ip-172-31-23-10~]$ vi wOrdtfit.c
Lec2-user@ip-172-31-23-10-]$ gcc Wordtfit.c -o wÊ
[ec2-user@ip-172-31-23-10 -1^/Wf
Process No Process Size Block No.
40
10
3 30 2
60 Not Allocated
EXPERIMENT -13
AIM:-Implementation of READER/WRITER problem using
semaphol
THEORY: -
The readers-writers problem relates to an ahiont euch as a fle that is
processes. Some of shared between muimple
these processes are readers i.e.,,they only want to read the data from the object
and some of the processes are
writers i.e. they want to write into the object.
The readers-writers problem is used to manage
the object data. For example - If two synchronization so that there are no problems Wu
readers access the
However, if two writers or a reader and writer access obiect
the
at the same time there 1s no proo
problems. obiect at the same time, there may Oo
To solve this situation, a writer should get
accessing the object, no reader or writer may exclusive
access it.
access to an object i.e. when a writer 15
object at the same time. However, multiple readers can access tne
This can be implemented using
reader-writer problem are given assemaphores.
follows -
The codes for the reader and writer
process in the
Reader Process
The code that defines the reader
process is given below
wait (mutex);
rc ++;

if (rc == 1)
wait (wrt);
signal(mutex);

READ THE OBJECT

wait(mutex);
rc --;

if (rc == 0)
signal (wrt);
signal (mutex);

Writer Process
The code that defines the writer process is given below:
wait(wrt);

WRITE INTO THE OBJECT

signal(wrt);

CODE:-
#include <stdio.h>
#include <stdlib.h>
#include <pthread.h>
#include <semaphore.h>
#include <unistd.h>

#define NUM READERS5


#define NUM WRITERS 2

sem tmutex; I/ Controls access to the shared


resource
sem twriteBlock: / Ensures exclusive access for writers
int readCount = 0; //Number of readers currently reading

void *reader(void *arg)


int id = *(int *)arg:
while (1){
Reader acquiring mutex to update readCount
sem_wait( &mute.
readCoutt;
H(readCount =1) {
sem wait(&writeBlock); // First reader blocks writers
sem_post(&mutex):

W
Reader reading the shared resource
printf("Reader %d is reading.\n", id);
sleep(rand() %3 t 1);
I/ Reader releasing mutex to update
readCount
sem_wait(&mutex);
readCount--;
if (readCount == 0) {

sem post(&writeBlock); / Last reader allows writers

sem _post(&mutex);
I/ Reader done reading
printf("Reader %d finished reading.\n", id);
sleep(rand() %3 + 1);

return NULL:

void *writer(void *arg) {


int id = *(int *)arg;
while (1){
writeBlock to get exclusive access
|/Writer acquiring
sem wait(&writeBlock);
te the shared resource
|/ Writer writing
printf("Writér %d is writing.\n", id);
slecp(fand() %3 + 1l);
MWriter done writing
writing.\n",, id);
printf("Writer %d finished
sleep(rand() %3 +l);
7Writer releasing writeBlnck to allow other readers/writers

sem_post(&writeBlock);

return NULL;

int main() {
srand(time(NULL));
I| Initialize semaphores
sem_init(&mutex, 0, 1):
sem init(&writeBlock, 0, 1);
|/ Create reader threads

pthread t readers[NUM_READERS];
int reader ids[NUM_READERS];
for (int i=0; i< NUM READERS; ++i) {
reader ids[i]= i;
pthread create(&readers[i], NULL, reader, &reader ids•i):

I/ Create writer threads


pthread_twriters[NUM_WRITERS];
int writer ids[NUM_WRITERS]:
for (int i= 0; i < NUM_ WRITERS; ++i)
writer ids[i]= i;
pthrcad create(&writers[i], NULL, writer, &writer_ ids[i]);

thrcads to finish
1/ Waít for reader
NUM_READERS; ++))
for (int i= 0; i<
pthrcad_join(readers[i], NULL);
1/Wait for writer thrcads to
finish
for (inti=0; i < NUM WRITERS; ++i) {
pthrcad_join(writers[i], NULL);

I/ Destroy semaphores
sem_destroy(&mutex);
scm_destroy(&writcBlock);
return 0:

OUTPUT: -

EitOE 1 inlshed vrlting

Mriter i anished veltlng


MrÁter 1 1 vriLpg
Vicer 1 inla

MeiterHVLELg

Krlcor 0.£inishied writing.

Mriter. colihed VEl:tn


wELter
ontshed vrscin

Reador 2
EXPERIMENT- 14
deadlock avoidance.
AIM: - Implementation of BANKER'S algorithmfor
THEORY: - avoidance algorithmthat
tests for
deadlock all
The banker's algorithm is a resource allocation and maximum possible amounts of
safety by simulating the allocation for the predetermined deciding whether
possible activities, before
Iresources, then makes an "s-state" check to test for
allocation should be allowed to continue.
Advantages
algorithm:
Following are the cssential characteristics of the Banker's
each proceSS.
resources that meet the requirements of
I. t Contains various for upcoming
resource
2. the operating system be held.
Each process should provide informationtolong
and how the resources will
requests, the number of resources, resource
process requests for each type of
and control
3. It helps the operating system manage
in the computer system. process can hold
attribute that represents indicates each
has a Max resource
4. The algorithm in a systemn.
the maximum number of resources

Disadvantages started in the


processes, and no additional processes can be
number of
1. It requires a fixed the process.
system while executing while
the processes to exchange its maximum needs
longer allows
The algorithm does no
2. processing its tasks.
requirement in advance for
to know and
state their maximum resource
has
3. Each process
the system. time, but the time limit for
resource requests can be granted in a finite
number of year.
4 The resources is one
allocating the

CODE: -
#include <stdio.h>

int main()

the Proccss names herc


P3. P4 are
LP0, P1, P2,
int n, m, i, j, k;
n=5;/ Number of processes
m =3; I/
Number of resources
t alloclSI[3] ={ {0, 1,0 }., I| PO / Allocation Matrix
{2, 0, 0 }, I/ PI
{3, 0, 2 }, I/P2
{2, 1, 1 }, // P3
Int
{0, 0, 2}};// P4
max[5][3] ={{7, 5, 3 }./ PO / MAX Matrix
{3, 2, 2 },1/ PI
{9, 0, 2}, / P2
{2, 2, 2 },// P3
{4,3, 3}:/P4
int avail[3] ={3,3, 2
};// Available Resources
int f[n], ans[n], ind = 0;
for (k =0; k<n;
k++) {
f[k] = 0;
}
int need[n][m];
for (i = 0; i< n; it) {
for (j = 0:j< m; j++)
need[i][i]= max[i][i]- alloc[i]i1;
int y = 0;
for (k =0; k < 5;kf) {
for(i =0; i<n; itt) {
if (f[i] == 0) {
int flag 0;
for (j = 0; j< m; jt+) {
if (need[JO)> avail[j]){
flag = 1;
break;

if (flag == 0) {
ans[ind++]= i;
for (y = 0; y <m; y++)
avail[y] += alloc[iJ[y]:
f[i] = 1;

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

if(f[i]-0)

flag-0;
printf("The following systemis-nof safe"):
break;

if(flag-1)
printf("Following
for (i
is the SAFE
Sequence\n");
=0; i
<n-1; it+)
printf(" P%d->", ans[i]);
printf(" P%d", ans[n - 1);

return (0):

OUTPUT: -

[ec2-user@ip-172-31-23-10 ~]_ vi banker.c


[ec2-user@ip-172-31-23-10~1^ qcc banker.co banker
[ec2-user@ip-172-31-23-10 -19-banker
Following is the SAFE sequence
P 1 > R3> P4 PO P2 ec2-user@ip-172-31-23-101$
EXPERIMENT -15
AJM:- Irnplenentation of DNING PHILOSOPHER problem.
THEORY:
p1loopher's problern is fhe classical nroblem of sypchronization which says thatrve
philosophers are sittíng around acircular table and their job is to thínk and eat alternatively. A
D noodles is placed at the center of he table along with five chopsticks ror ca
phalosophers. Toct aphilosopher needs both theirright and aleft chopstick A phlosopihoth
i7 both imnedizte left and right chonsticks ofthe philosopher is available. In case i Do
I1d1Zte left and right chonstícks of the nhilosonher are not available then the philosopnei Pus
down their (either left or right) chopstíck and starts thínking again.

CODE:
inciuds <sáioh
#include <sálib.h

#includepthrced.h
inciude unistdh

PHILOSOPHERS 5
#define NUM
3
#dcfine NUM EATING ITERATIONS

forks[UM_PHILOSOPHERS]:
pthrcad rmutez t
ptfhrczdtphilosophers[NUM PHILOSOPHERS]:
"philosophervoid arg) !
void
*jarg:
int id = *(int
= id;
int leftfork NUM_PHILOSOPHERS:
Aa- 1) %
int ríght_fork EATING_ITERATIONS; t+i) !
S0:i- NUM E
fur (int
Thinking n", jd):
thínking.
príntf("Philosopher%d is
sleeplrand)%,3 - l);
|/Pick up left
fork
pthread_mutex lock(&forks[left _fork]);
printf("Philosopher od picked up left fork.\n", id);
|/Pick up right
fork
pthread_mutex lock(&forks[right _fork]);
printf("Philosopher %d picked up right fork.\n", id):
I/ Eating

printf("Philosopher %d is cating. \n", id);


sleep(rand) %3 +1);
I/Put down right fork

pthread_mutex_unlock(&forks[right_fork]);
printf("Philosopher %d put down right fork. \n", id);
|/Put down left fork

pthread mutex_unlock(&forks[left_fork]);
printf("Philosopher %d put down left fork.\n", id);

return NULL:

int main() {
srand(time(NULL));
1/ Initialize forks muteXes

for (int i= 0; i<NUM _PHILOSOPHERS; ++i)


pthread_mutex_init(&forks[i], NULL):

thrcads
/Crcatc philosopher
int philosopher_ids|NUM_PHILOSOPHERS):
i<NUM PHILOSOPHERS; +ti) {
forint i = 0;
philosopher_ids[i] -i:
pthread Create(&philosophers[i], NULL, philosopher, &philosopher_ids[):

1/ Wait for
philosopher threads to finish
for (int i= 0; i<NUM
PHILOSOPHERS; +i){
pthread join(philosophers[i], NULL);

I/Destroy forks mutexes


for (int i=0; i< NUM PHILOSOPHERS; ++i) {

pthread mutex_destroy(&forks[i):

return 0:

OUTPUT: -

Osei-172-21-3-10
DR
tec2-serip-172 3
Iec2-ertip-l231
hintig
Filos inàg

2b t h i o
Osopber TE ork
AilosopesG thin
Fhlogopbe ning

ber 0 ork.
ebiloso Dber3
ehiloscpr
tnng

losopber

Philao
ork

Losopher
ork
1 put cht
Rork
legt tor

2 3 - - 1 0 JS
Pbiloe
PhilosopherEhilnsOph
RhilosOpher Ehilosopher
thining sPhilasophe
Ehilogopher
thiRking is Ehlosopher
Ehosopher
thnihg downPhilosopher3
Bhilosopher
PhilosoRhe thinkihg
thìnking
Iis0
pUtPhilosophex
ehilosopher
(ec2-usereipl721-2310
Philosophe
thinkangthinking i /dp
Philosopher

Put 2
Ls
thinRDOS
dowghe Chinking

OR

You might also like