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

Central University of Karnataka

Dept.: ECE Dept.

(Established by an Act of the Parliament in 2009) Curriculum

School of Engineering
Syllabus Contents

w.e.f. 2024-25

Real-Time Operating System


Lab Manual

6th semester

Kadaganchi, Aland Road, Kalaburagi 585 367, Karnataka, India.


Website: www.cuk.ac.in
Central University of Karnataka
Dept.: ECE Dept.

(Established by an Act of the Parliament in 2009) Curriculum

School of Engineering
Syllabus Contents

w.e.f. 2024-25

TABLE OF CONTENTS

Experiment Page
List of Experiments
No. No.
CPU Scheduling Algorithms 3-13

1. First Come First Serve (FCFS) Scheduling Algorithm 4-6

2. Round Robin Scheduling Algorithm 7-10

3. Priority Based Scheduling Algorithm 11-13

Process Creation in FreeRTOS 14-16

4. Implementation of Task Creation and Deletion in FreeRTOS 15


Implementation of Task Suspension and Resuming in
5. 16
FreeRTOS
Memory Management Techniques 17-22
Multiprogramming with a Fixed number of Tasks (MFT)
6. 18-20
Memory Management Techniques
Multiprogramming with a Variable number of Tasks (MVT)
7. 21-22
Memory Management Techniques
Deadlock Detection Algorithm 23-33

8. Study and implementation of Semaphore 24-25

9. Bankers Algorithm for Deadlock Avoidance 26-29

10. Simulate the concept of Dining-Philosophers Problem 30-33

Kadaganchi, Aland Road, Kalaburagi 585 367, Karnataka, India.


Website: www.cuk.ac.in
Central University of Karnataka
Dept.: ECE Dept.

(Established by an Act of the Parliament in 2009) Curriculum

School of Engineering
Syllabus Contents

w.e.f. 2024-25

CPU Scheduling Algorithm


CPU Scheduling is a process that allows one process to use the CPU while another process is delayed (in
standby) due to unavailability of any resources such as I / O etc, thus making full use of the CPU. The
purpose of CPU Scheduling is to make the system more efficient, faster, and fairer.
Objectives of Process Scheduling Algorithm:-
 Utilization of CPU at maximum level. Keep the CPU as busy as possible.
 Allocation of CPU should be fair.
 Throughput should be Maximum. i.e. Number of processes that complete their execution per time
unit should be maximized.

Terminologies used in CPU Scheduling:-


 Arrival Time: In CPU scheduling, arrival time is the moment when a process enters the ready queue
and is ready for execution by the CPU. It's the point when a process becomes eligible for scheduling.
 Burst Time: Burst time is the amount of CPU time a process requires to complete its execution. It is
also known as "execution time" or "running time".
 Exit Time: Exit time is the time when a process completes its execution and exit from the system.
 Completion time (CT): Completion time is the time at which the process has been terminated.
 Waiting Time: Waiting time (WT) in an operating system is the total time a process spends in a
ready queue before it reaches the CPU. It's the time between the process's arrival in the ready queue
and the start of its execution.
 Average Waiting Time (AWT): Ratio of Total Waiting Time and the Number of Processes.
 Turnaround Time: In CPU scheduling, turnaround time (TAT) is the time between when a process is
submitted and when it's completed. It's the sum of the time spent waiting for memory, waiting in the
ready queue, executing on the CPU, and doing I/O.
 Average Turn Around Time (ATAT): Ratio of Total Turnaround Time and the Number of Processes.
 Gantt Chart: A Gantt chart is a horizontal bar chart that shows operating systems CPU scheduling. It
can help plan, coordinate, and track CPU utilization factors like throughput, waiting time, and
turnaround time.

Kadaganchi, Aland Road, Kalaburagi 585 367, Karnataka, India.


Website: www.cuk.ac.in
Central University of Karnataka
Dept.: ECE Dept.

(Established by an Act of the Parliament in 2009) Curriculum

School of Engineering
Syllabus Contents

w.e.f. 2024-25

Types of CPU Scheduling Algorithms:-


1. First Come First Serve (FCFS) CPU Scheduling Algorithm
FCFS Scheduling algorithm automatically executes the queued processes and requests in the order of
their arrival. It allocates the job that first arrived in the queue to the CPU, then allocates the second
one, and so on. FCFS is the simplest and easiest CPU scheduling algorithm.
Characteristics of FCFS Scheduling:
 FCFS follows a non-preemptive approach,
meaning, once the CPU lets a process take
control, it won’t preempt until the job
terminates.
 It follows the criteria of arrival time for the
selection process.
 The processor selects the very first job in the
ready queue, and it runs till completion.
 The algorithm is feasible to use and
implement in the long run.
 The process is not very complicated, thus
easy to understand.
Real-World Examples:
 Buying a movie ticket: The first person in line gets to buy the ticket first.
 Shopping mall billing counter: The first person in line gets their bill done first.
Procedure followed in FCFS Algorithm:
Consider the following table for arrival time and burst time for 5 processes P1, P2, P3, P4, P5,
Processes Arrival Time Burst Time
P1 0 4
P2 1 3
P3 2 1
P4 3 2
P5 4 5
The process begins with P1 as it has an arrival time of 0. So, at first, the CPU is scheduled to perform
process 1 that is having burst time of 4. Then process 2 and so on till process 5.
Turn Around Time is calculated as, T.A.T. = C.T. (Completion Time) – A.T. (Arrival Time).
Waiting Time is calculated as, W.T. = T.A.T. – B.T. (Burst Time).
Processes Arrival Time Burst Time C.T. T.A.T W.T.
A 0 4 4 4 0
B 1 3 7 6 3
C 2 1 8 6 5
D 3 2 10 7 5
E 4 5 15 11 6

Kadaganchi, Aland Road, Kalaburagi 585 367, Karnataka, India.


Website: www.cuk.ac.in
Central University of Karnataka
Dept.: ECE Dept.

(Established by an Act of the Parliament in 2009) Curriculum

School of Engineering
Syllabus Contents

w.e.f. 2024-25

( )
Average Waiting Time (Avg. W.T.) = = = = 3.8

( )
Average Turn Around Time (Avg. T.A.T.) = = = = 6.8

Code:
#include<stdio.h>
int main()
{
int bt[10]={0},at[10]={0},tat[10]={0},wt[10]={0},ct[10]={0};
int n;
float totalTAT=0,totalWT=0;
printf("Enter the no of processes\n");
scanf("%d",&n);
printf("\nEnter arrival time and burst time for each process:- \n");
for(int i=0;i<n;i++)
{
printf("Arriva time of process[%d]\t",i+1);
scanf("%d",&at[i]);
printf("Burst time of process[%d]\t",i+1);
scanf("%d",&bt[i]);
printf("\n");
}
//calculating completion time
int sum=at[0];
for(int j=0;j<n;j++)
{
sum=sum+bt[j];
ct[j]=sum;
}
//calculate turnaround time and waiting time
for(int k=0;k<n;k++)
{
tat[k]=ct[k]-at[k];
totalTAT=totalTAT+tat[k];
}
for(int k=0;k<n;k++)
{
wt[k]=tat[k]-bt[k];
totalWT=totalWT+wt[k];
}
printf("p#\t AT\t BT\t CT\t TAT\t WT\t\n\n");
for(int i=0;i<n;i++)
{

Kadaganchi, Aland Road, Kalaburagi 585 367, Karnataka, India.


Website: www.cuk.ac.in
Central University of Karnataka
Dept.: ECE Dept.

(Established by an Act of the Parliament in 2009) Curriculum

School of Engineering
Syllabus Contents

w.e.f. 2024-25

printf("P%d\t %d\t %d\t %d\t %d\t %d\n",i+1,at[i],bt[i],ct[i],tat[i],wt[i]);


}
printf("\n\nAverage turnaround time=%f\n",totalTAT/n);
printf("Average Waiting time=%f\n\n",totalWT/n);
return 0;
}

Output:

Kadaganchi, Aland Road, Kalaburagi 585 367, Karnataka, India.


Website: www.cuk.ac.in
Central University of Karnataka
Dept.: ECE Dept.

(Established by an Act of the Parliament in 2009) Curriculum

School of Engineering
Syllabus Contents

w.e.f. 2024-25

2. Round Robin CPU Scheduling Algorithm


The Round robin scheduling algorithm is one of the CPU scheduling algorithms in which every
process gets a fixed amount of time quantum or time slice to execute the process. In this algorithm,
every process gets executed cyclically. This means that processes that have their burst time remaining
after the expiration of the time quantum are sent back to the ready state and wait for their next turn to
complete the execution until it terminates.

Characteristics of Round Robin Scheduling in OS:


 Round robin scheduling in os is clock-driven (Hybrid model).
 The round-robin algorithm generally focuses on the Time sharing technique.
 Round robin Scheduling is the simplest and one of the oldest algorithms.
 This algorithm is a real-time algorithm as it responds to an event within a specific time limit.
 Round robin is a widely used algorithm in traditional OS.

Real-World Example:
 In sports teams like those found in the NFL, NBA, MLB or NHL, a round-robin is a method of
scheduling where each participant plays against all other participants in the event. Like in Cricket
World Cups where a team plays against all other teams in the League Stage.

Procedure followed in Round Robin Algorithm:


Consider the following 6 processes: P1, P2, P3, P4, P5, and P6 with their arrival time and burst time
as given below:

Kadaganchi, Aland Road, Kalaburagi 585 367, Karnataka, India.


Website: www.cuk.ac.in
Central University of Karnataka
Dept.: ECE Dept.

(Established by an Act of the Parliament in 2009) Curriculum

School of Engineering
Syllabus Contents

w.e.f. 2024-25

Process ID Arrival Time Burst Time


P1 0 5
P2 1 6
P3 2 3
P4 3 1
P5 4 5
P6 6 4
Time Quantum is 4 units.
Step1: At first, In the ready queue, process P1 will be executed for a time slice of 4 units. Since there are no
processes initially, Process P1, with a burst time of 5 units, will be the only process in the ready queue.
Step 2: Along with the execution of P1, four more processes, P2, P3, P4, and P5, arrive in the ready queue.
P1 will be added to the ready queue due to the remaining 1 unit.
Step 3: During the execution of P2, P6 arrived in the ready queue. Since P2 has not been completed, P2 will
be added to the ready queue.
P3 P4 P5 P1 P6 P2
3 1 5 1 4 2
Step 4: Similarly, P3 and P4 have been completed, but P5 has a remaining burst time of 1 unit. Hence it will
be added back to the queue.
Step 5: The next processes, P6 and P2, will be executed. Only P5 will be left with 1 unit of burst time.

Processes Arrival Time Burst Time C.T. T.A.T W.T.


A 0 5 17 17 12
B 1 6 23 22 16
C 2 3 11 9 6
D 3 1 12 9 8
E 4 5 24 20 15
F 6 4 21 15 11

( )
Average Waiting Time (Avg. W.T.) = = = = 11.833

( )
Average Turn Around Time (Avg. T.A.T.) = = = = 15.833

Kadaganchi, Aland Road, Kalaburagi 585 367, Karnataka, India.


Website: www.cuk.ac.in
Central University of Karnataka
Dept.: ECE Dept.

(Established by an Act of the Parliament in 2009) Curriculum

School of Engineering
Syllabus Contents

w.e.f. 2024-25
Code:
#include<stdio.h>
int main()
{
int count, j, n, time, remain, flag=0,timeQuantum;
int wait_time=0,turnaround_time=0,at[10],bt[10],rt[10];
printf("Enter Total Process:\t ");
scanf("%d",&n);
remain=n;
for(count=0;count<n;count++)
{
printf("Enter Arrival Time and Burst Time for Process Process Number %d :\n",count+1);
scanf("%d",&at[count]);
scanf("%d",&bt[count]);
rt[count]=bt[count];
}
printf("Enter Time Quantum:\t");
scanf("%d",&timeQuantum);
printf("\n\nProcess\t|Turnaround Time|Waiting Time\n\n");
for(time=0,count=0;remain!=0;)
{
if(rt[count]<=timeQuantum && rt[count]>0)
{
time+=rt[count];
rt[count]=0;
flag=1;
}
else if(rt[count]>0)
{
rt[count]-=timeQuantum;
time+=timeQuantum;
}
if(rt[count]==0 && flag==1)
{
remain--;
printf("P[%d]\t|\t%d\t|\t%d\n",count+1,time-at[count],time-at[count]-bt[count]);
wait_time+=time-at[count]-bt[count];
turnaround_time+=time-at[count];
flag=0;
}
if(count==n-1)
count=0;
else if(at[count+1]<=time)
count++;
else
count=0;
}
Kadaganchi, Aland Road, Kalaburagi 585 367, Karnataka, India.
Website: www.cuk.ac.in
Central University of Karnataka
Dept.: ECE Dept.

(Established by an Act of the Parliament in 2009) Curriculum

School of Engineering
Syllabus Contents

w.e.f. 2024-25

printf("\nAverage Waiting Time= %f\n",wait_time*1.0/n);


printf("Avg Turnaround Time = %f",turnaround_time*1.0/n);
return 0;
}

Output:

Kadaganchi, Aland Road, Kalaburagi 585 367, Karnataka, India.


Website: www.cuk.ac.in
Central University of Karnataka
Dept.: ECE Dept.

(Established by an Act of the Parliament in 2009) Curriculum

School of Engineering
Syllabus Contents

w.e.f. 2024-25

3. Priority Based CPU Scheduling Algorithm


In Priority scheduling, there is a priority number assigned to each process. In some systems, the lower
the number, the higher the priority. While, in the others, the higher the number, the higher will be the
priority. The Process with the higher priority among the available processes is given to the CPU.

Characteristics of Priority Scheduling


 A CPU algorithm that schedules processes based
on priority.
 It used in Operating systems for performing batch
processes.
 If two jobs having the same priority are READY,
it works on a FIRST COME, FIRST SERVED
basis.
 In priority scheduling, a number is assigned to
each process that indicates its priority level.
 Lower the number, higher is the priority.

Real-World Example:
 In a hospital, patients are attended to based on the severity of their conditions, not just their arrival time.
 Scheduling our day-to-day tasks based on priority (or importance).

Procedure followed in Priority Based Algorithm:


Consider following five processes P1 to P5. Each process has its unique priority, burst time.
Process Priority Burst Time
A 1 4
B 2 3
C 1 7
D 3 4
E 2 2

Step 1: At time=0, Process P1 and P2 arrive. P1 has higher priority than P2. The execution begins with
process P1, which has burst time 4. At time=1, no new process arrive. Execution continues with P1.
Step 2: At time 2, no new process arrives, so you can continue with P1. P2 is in the waiting queue.
Step 3: At time 3, no new process arrives so you can continue with P1. P2 process still in the waiting.
Step 4: At time 4, P1 has finished its execution. P2 starts execution.
Step 5: At time= 5, no new process arrives, so we continue with P2.

Kadaganchi, Aland Road, Kalaburagi 585 367, Karnataka, India.


Website: www.cuk.ac.in
Central University of Karnataka
Dept.: ECE Dept.

(Established by an Act of the Parliament in 2009) Curriculum

School of Engineering
Syllabus Contents

w.e.f. 2024-25

Step 6: At time=6, P3 arrives. P3 is at a higher priority (1) compared to P2 having priority (2). P2 is
preempted, and P3 begins its execution. Like this continue till all the processes are executed.

Turnaround Waiting
Process Burst Time Priority
Time Time
A 4 1 4 0
C 7 1 11 4
B 3 2 14 11
E 2 2 16 14
D 4 3 20 16

( )
Average Waiting Time (Avg. W.T.) = = = = 9.00

( )
Average Turn Around Time (Avg. T.A.T.) = = = = 13.00

Code:
#include<stdio.h>
int main()
{
int p[20],bt[20],pri[20], wt[20],tat[20],i, k, n, temp;
float wtavg, tatavg;
printf("Enter the number of processes --- ");
scanf("%d",&n);
for(i=0;i<n;i++)
{
p[i] = i;
printf("Enter the Burst Time & Priority of Process %d --- \n",i);
scanf("%d %d",&bt[i], &pri[i]);
}
for(i=0;i<n;i++)
{
for(k=i+1;k<n;k++)
{
if(pri[i] > pri[k])
{
temp=p[i];
p[i]=p[k];
p[k]=temp;

Kadaganchi, Aland Road, Kalaburagi 585 367, Karnataka, India.


Website: www.cuk.ac.in
Central University of Karnataka
Dept.: ECE Dept.

(Established by an Act of the Parliament in 2009) Curriculum

School of Engineering
Syllabus Contents

w.e.f. 2024-25
temp=bt[i];
bt[i]=bt[k];
bt[k]=temp;
temp=pri[i];
pri[i]=pri[k];
pri[k]=temp;
}
}
}
wtavg = wt[0] = 0;
tatavg = tat[0] = bt[0];
for(i=1;i<n;i++)
{
wt[i] = wt[i-1] + bt[i-1];
tat[i] = tat[i-1] + bt[i];

wtavg = wtavg + wt[i];


tatavg = tatavg + tat[i];
}
printf("\nPROCESS\t\tPRIORITY\tBURST TIME\tWAITING TIME\tTURNAROUND TIME");
for(i=0;i<n;i++)
{
printf("\n%d \t\t %d \t\t %d \t\t %d \t\t %d ",p[i],pri[i],bt[i],wt[i],tat[i]);
}
printf("\nAverage Waiting Time is --- %f",wtavg/n);
printf("\nAverage Turnaround Time is --- %f",tatavg/n);
}
Output:

Kadaganchi, Aland Road, Kalaburagi 585 367, Karnataka, India.


Website: www.cuk.ac.in
Central University of Karnataka
Dept.: ECE Dept.

(Established by an Act of the Parliament in 2009) Curriculum

School of Engineering
Syllabus Contents

w.e.f. 2024-25

Process Creation in FreeRTOS


A process is defined as an entity that represents the basic unit of work to be implemented in the system. To
put it in simple terms, we write our computer programs in a text file and when we execute this program, it
becomes a process that performs all the tasks mentioned in the program.
When a program is loaded into the memory and it becomes a process, it can be divided into four sections:-
stack, heap, text, and data.
 Stack: The process Stack contains the temporary data such as
method/function parameters, return address and local
variables.
 Heap: This is dynamically allocated memory to a process
during its run time.
 Text: This includes the current activity represented by the
value of Program Counter and the contents of the processor's
registers.
 Data: This section contains the global and static variables.

Process Life Cycle:-

A task is a unit of work or


execution in a software
application. The operating system
(OS) typically manages task
execution in an embedded
processor. Example of tasks on a
computer: Cut, copy, and paste.

FreeRTOS is a real-time
operating system (RTOS) kernel
for embedded devices. It is open
source and is distributed under
the MIT License. FreeRTOS is
designed to make it easier to
program, deploy, secure, connect,
and manage small, low-power
edge devices.

Kadaganchi, Aland Road, Kalaburagi 585 367, Karnataka, India.


Website: www.cuk.ac.in
Central University of Karnataka
Dept.: ECE Dept.

(Established by an Act of the Parliament in 2009) Curriculum

School of Engineering
Syllabus Contents

w.e.f. 2024-25

4. Implementation of Task Creation and Deletion in FreeRTOS.


Task creation is the process of creating a task in FreeRTOS. This is done using the FreeRTOS API
xTaskCreate, which creates a task in memory. The
API also creates a task control block and stack
space for the task. To use a task in FreeRTOS, you API stands for Application Programming Interface.
also need to write a function that implements the It's a software intermediary that allows two
applications to communicate and work together.
task. This function is called the task handler, which
executes the task's code.
In FreeRTOS, a task can delete itself by calling either vTaskDelete( NULL ); or vTaskDelete(
my_handle ). In this, my_handle is a variable of type xTaskHandle that holds the calling tasks
handle. The task being deleted will be removed from all ready, blocked, suspended, and event lists.
The memory allocated to the task for the task stack and task control block are freed the next time the
idle task runs.
Code: (Arduino IDE)
#include <Arduino_FreeRTOS.h>
TaskHandle_t TaskHandle_1; Type by which tasks are referenced. For example, a call to
TaskHandle_t TaskHandle_2; xTaskCreate returns (via a pointer parameter) an
TaskHandle_t TaskHandle_3; TaskHandle_t variable that can then be used as a
void setup() parameter to vTaskDelete to delete the task.
{
Serial.println("In Setup Function");
Serial.begin(9600);
xTaskCreate(MyTask1,"Task1",100,NULL,1,&TaskHandle_1);
xTaskCreate(MyTask2,"Task2",100,NULL,2,&TaskHandle_2);
xTaskCreate(MyTask3,"Task3",100,NULL,3,&TaskHandle_3);
}
void loop()
{
Serial.println("Loop function");
}
static void MyTask1(void* pvParameters)
{
Serial.println("Task1, Deleting Itself");
vTaskDelete(NULL);
}
static void MyTask2(void* pvParameters)
{
Serial.println("Task2, Deleting Itself");
vTaskDelete(NULL);
}
static void MyTask3(void* pvParameters)
{
Serial.println("Task3, Deleting Itself");
vTaskDelete(NULL);
}

Kadaganchi, Aland Road, Kalaburagi 585 367, Karnataka, India.


Website: www.cuk.ac.in
Central University of Karnataka
Dept.: ECE Dept.

(Established by an Act of the Parliament in 2009) Curriculum

School of Engineering
Syllabus Contents

w.e.f. 2024-25

Output onSerial Monitor of Arduino IDE


5. Implementation of Task Suspension and Resuming in FreeRTOS.
In FreeRTOS, a task can be suspended by calling the function vTaskSuspend(). When a task is suspended,
it will remain in that state until it is resumed. A task will not
receive any microcontroller processing time while it is suspended,
regardless of its priority.
The vTaskResume() function resumes a suspended task. To
resume a task, you must pass the handle of the task to be resumed.
If the resumed task has a higher priority than the running task, it
will preempt the running task. Otherwise, it will remain in a ready
state.
Code: (Arduino IDE)
#include <Arduino_FreeRTOS.h>
TaskHandle_t TaskHandle_1;
TaskHandle_t TaskHandle_2;
void setup()
{
Serial.begin(9600);
Serial.println("In Setup Function");
xTaskCreate(MyTask1,"Task1",100,NULL,1,&TaskHandle_1);
xTaskCreate(MyTask2,"Task2",100,NULL,2,&TaskHandle_2);
xTaskCreate(MyTask3,"Task3",100,NULL,3,&TaskHandle_3);
}
void loop()
{
Serial.println("Loop function");
}
static void MyTask1(void* pvParameters)
{
Serial.println("Task1 Resuming Task2");
vTaskResume(TaskHandle_2);
Serial.println("Task1 Resuming Task3");
vTaskResume(TaskHandle_3);
Serial.println("Task1 Deleting Itself");
vTaskDelete(TaskHandle_1);
}
static void MyTask2(void* pvParameters)
{
Serial.println("Task2, Deleting Itself");
vTaskDelete(NULL);
}
static void MyTask3(void* pvParameters)

Output on Serial Monitor of Arduino IDE

Kadaganchi, Aland Road, Kalaburagi 585 367, Karnataka, India.


Website: www.cuk.ac.in
Central University of Karnataka
Dept.: ECE Dept.

(Established by an Act of the Parliament in 2009) Curriculum

School of Engineering
Syllabus Contents

w.e.f. 2024-25

Memory Management Techniques


The term memory can be defined as a collection of data in a specific format. It is used to store
instructions and process data. The memory comprises a large array or group of words or bytes, each
with its own location. The primary purpose of a computer system is to execute programs. These
programs, along with the information they access, should be in the main memory during execution.
The CPU fetches instructions from memory according to the value of the program counter. To achieve
a degree of multiprogramming and proper utilization of memory, memory management is important.

Multiprogramming is a type of parallel processing that allows multiple


programs to run at the same time on a single processor system. The operating
system (OS) allocates CPU time to different programs so that it appears as if
they are all running simultaneously. Here's an example of
multiprogramming: A user can use MS-Excel, download apps, transfer data,
and use a browser all at the same time

Why Memory Management is Required? Fragmentation refers to a process of


 Allocate and de-allocate memory before and after information storage where the system’s memory
space is used inadequately, thus reducing the
process execution. overall efficiency or ability. Cause of
 To keep track of used memory space by processes. Fragmentation: This can happen when a file is
 To minimize fragmentation issues. too large to fit into a single contiguous block of
free space on the storage medium, or when the
 To proper utilization of main memory. blocks of free space on the medium are
 To maintain data integrity while executing of process. insufficient to hold the file.

Fixed partitioning is a memory management technique that divides memory into fixed, non-
overlapping sizes. It's the oldest and simplest technique for loading multiple processes into main
memory. In fixed partitioning, the partitions are created in the main memory before execution or
during the system configuration. The number of partitions in RAM is fixed, but the sizes of the
partitions can vary.
 In fixed partitioning concept, RAM is divided into set of fixed partition of equal Size
 Programs having the Size Less than the partition size are loaded into Memory
 Programs Having Size more then the size of Partitions Size is rejected
 The program having the size less than the partition size will lead to internal Fragmentation.
 If all partitions are allocated and a new program is to be loaded, the program that lead to
Maximum Internal Fragmentation can be replaced.

Dynamic partitioning is a memory allocation technique used in operating systems. It creates


partitions for each process or memory request. The size of the partitions matches the size of the
request. It has no internal fragmentation but it is difficult to implement.
 Initially RAM is portioned according to the of programs to be loaded into
 Memory till such time no other program can be loaded.
 The Left over Memory is called a hole which is too small too fit any process.
 When a new program is to be into Memory Look for the partition, which leads to least
External fragmentation and load the Program.
 The space that is not used in a partition is called as External Fragmentation

Kadaganchi, Aland Road, Kalaburagi 585 367, Karnataka, India.


Website: www.cuk.ac.in
Central University of Karnataka
Dept.: ECE Dept.

(Established by an Act of the Parliament in 2009) Curriculum

School of Engineering
Syllabus Contents

w.e.f. 2024-25

Internal fragmentation: Internal fragmentation occurs when memory blocks are allocated to the
process more than their requested size. Due to this some unused space is left over and creating an
internal fragmentation problem. Example: Suppose there is a fixed partitioning used for memory
allocation and the different sizes of blocks 3MB, 6MB, and 7MB space in memory. Now a new
process p4 of size 2MB comes and demands a block of memory. It gets a memory block of 3MB but
1MB block of memory is a waste, and it can not be allocated to other processes too. This is called
internal fragmentation.

External fragmentation: In External Fragmentation, we have a free memory block, but we can not
assign it to a process because blocks are not contiguous. Example: Suppose (consider the above
example) three processes p1, p2, and p3 come with sizes 2MB, 4MB, and 7MB respectively. Now
they get memory blocks of size 3MB, 6MB, and 7MB allocated respectively. After allocating the
process p1 process and the p2 process left 1MB and 2MB. Suppose a new process p4 comes and
demands a 3MB block of memory, which is available, but we can not assign it because free memory
space is not contiguous. This is called external fragmentation.

Real-World Example:
 Download software, transfer data, Google Chrome, MS Excel, Firefox browser, and many other apps
are instances of multiprogramming operating systems.

6. Multiprogramming with a Fixed number of Tasks (MFT) Memory Management Technique.


MFT stands for Multiprogramming with a Fixed number of Tasks. It is a memory management
technique that divides memory into fixed-size partitions. It is one of the old memory management
techniques in which the memory is partitioned into fixed size partitions and each job is assigned to a
partition. The memory assigned to a partition does not change.

Characteristics of MFT:
 Simple
 A fixed number of jobs at a time and this is
known
 No frequent switching of boundary registers
 Fences are fixed
 The OS is catered for a number of PCB's
 The strategy can be used along with
swapping.

Kadaganchi, Aland Road, Kalaburagi 585 367, Karnataka, India.


Website: www.cuk.ac.in
Central University of Karnataka
Dept.: ECE Dept.

(Established by an Act of the Parliament in 2009) Curriculum

School of Engineering
Syllabus Contents

w.e.f. 2024-25

Code:
#include<stdio.h>
Int main()
{
int i,p=0;
int ms, bs, nob, ef,n, mp[10],tif=0;
printf("Enter the total memory available (in Bytes) -- ");
scanf("%d",&ms);
printf("Enter the block size (in Bytes) -- ");
scanf("%d", &bs);
nob=ms/bs;
ef=ms - nob*bs;
printf("\nEnter the number of processes -- ");
scanf("%d",&n);
for(i=0;i<n;i++)
{
printf("Enter memory required for process %d (in Bytes)-- ",i+1);
scanf("%d",&mp[i]);
}
printf("\nNo. of Blocks available in memory -- %d",nob);
printf("\n\nPROCESS\tMEMORY REQUIRED\tALLOCATED INTERNAL
FRAGMENTATION");
for(i=0;i<n && p<nob;i++)
{
printf("\n %d\t\t%d",i+1,mp[i]);
if(mp[i] > bs)
printf("\tNO\t\t---");
else
{
printf("\tYES\t\t%d",bs-mp[i]);
tif = tif + bs-mp[i];
p++;
}
}
if(i<n)
printf("\nMemory is Full, Remaining Processes cannot be accomodated");
printf("\n\nTotal Internal Fragmentation is %d",tif);
printf("\nTotal External Fragmentation is %d",ef);
}

Explanation:
The program calculates the number of blocks available (nob) based on the total memory and block
size. It also calculates the external fragmentation (ef) by subtracting the total memory occupied by
allocated blocks from the total memory available.
Then, the program iterates through each process, asking for the memory required for each. For each
process, it checks if the memory requirement is greater than the block size. If it is, it prints "NO"
Kadaganchi, Aland Road, Kalaburagi 585 367, Karnataka, India.
Website: www.cuk.ac.in
Central University of Karnataka
Dept.: ECE Dept.

(Established by an Act of the Parliament in 2009) Curriculum

School of Engineering
Syllabus Contents

w.e.f. 2024-25

indicating that the process cannot be accommodated in a single block. If the memory requirement is
less than or equal to the block size, it prints "YES" and the allocated internal fragmentation, which is
the difference between the block size and the memory requirement.
The program keeps track of the total internal fragmentation (tif) by adding up the internal
fragmentation for each successfully allocated process. The variable p is used to count the number of
processes that have been successfully allocated so far.
Finally, the program prints the total internal and external fragmentation. If there are still processes
remaining after all the available blocks are filled, it prints a message stating that the memory is full,
and the remaining processes cannot be accommodated.

Output:

Kadaganchi, Aland Road, Kalaburagi 585 367, Karnataka, India.


Website: www.cuk.ac.in
Central University of Karnataka
Dept.: ECE Dept.

(Established by an Act of the Parliament in 2009) Curriculum

School of Engineering
Syllabus Contents

w.e.f. 2024-25

7. Multiprogramming with a Variable number of Tasks (MVT) Memory Management Technique.


MVT stands for Multiprogramming with a Variable Number of Tasks. It's a memory allocation
scheme that lets multiple programs run simultaneously in a shared memory space. MVT is a memory
management technique that gives each job the amount of memory it needs. MVT allows partition
sizes to vary dynamically. As many jobs as can fit in memory are loaded.

Characteristics of MVT:
 It divides memory into fixed-size
partitions, and each partition is
assigned to a process.
 It is a memory management
technique in which each job
receives the amount of memory it
needs.
 It uses variable fences, while MFT
uses fixed fences.
 It significantly reduces internal
fragmentation and can correct
external fragmentation.

Code:
#include<stdio.h>
int main()
{
char ch = 'y';
int ms,mp[10],i, temp,n=0;
printf("\nEnter the total memory available (in Bytes)-- ");
scanf("%d",&ms);
temp=ms;
for(i=0;ch=='y';i++,n++)
{
printf("\nEnter memory required for process %d (in Bytes) -- ",i+1);
scanf("%d",&mp[i]);
if(mp[i]<=temp)
{
printf("\nMemory is allocated for Process %d ",i+1);
temp = temp - mp[i];
}
else
{
printf("\nMemory is Full");
break;
}
printf("\nDo you want to continue(y/n) -- ");
scanf(" %c", &ch);
}
Kadaganchi, Aland Road, Kalaburagi 585 367, Karnataka, India.
Website: www.cuk.ac.in
Central University of Karnataka
Dept.: ECE Dept.

(Established by an Act of the Parliament in 2009) Curriculum

School of Engineering
Syllabus Contents

w.e.f. 2024-25
printf("\n\nTotal Memory Available -- %d", ms);
printf("\n\n\tPROCESS\t\t MEMORY ALLOCATED ");
for(i=0;i<n;i++)
printf("\n \t%d\t\t%d",i+1,mp[i]);
printf("\n\nTotal Memory Allocated is %d",ms-temp);
printf("\nTotal External Fragmentation is %d",temp);
}

Output:

Kadaganchi, Aland Road, Kalaburagi 585 367, Karnataka, India.


Website: www.cuk.ac.in
Central University of Karnataka
Dept.: ECE Dept.

(Established by an Act of the Parliament in 2009) Curriculum

School of Engineering
Syllabus Contents

w.e.f. 2024-25

Deadlock Detection Algorithm


A deadlock in an operating system (OS) is a situation where two or more processes are unable to
proceed because each process is waiting for a resource that is being held by another process.
Example:
 Consider an example when two trains are coming toward each other on the same track and there
is only one track, none of the trains can move once they are in front of each other.
 A similar situation occurs in operating systems when there are two or more processes that hold
some resources and wait for resources held by other(s).
 For example, in the below diagram, Process 1 is holding Resource 1 and waiting for resource 2
which is acquired by process 2, and process 2 is waiting for resource 1.

A deadlock detection algorithm is a technique used by an operating system to identify deadlocks. It


checks the status of processes and resources to determine if a deadlock has occurred. If a deadlock is
detected, a separate algorithm can help eliminate the deadlock.

Advantages:
 Improved System Stability
 Better Resource Utilization
 Easy Implementation (like Wait-For Graph)

Disadvantages:
 Performance Overhead
 Complex (some algorithms like Resource Allocation Graph, etc)

Kadaganchi, Aland Road, Kalaburagi 585 367, Karnataka, India.


Website: www.cuk.ac.in
Central University of Karnataka
Dept.: ECE Dept.

(Established by an Act of the Parliament in 2009) Curriculum

School of Engineering
Syllabus Contents

w.e.f. 2024-25

8. Study and implementation of Semaphore


A semaphore is a variable that controls access to shared resources in an operating system (OS). It is
a synchronization tool that allows multiple processes to share a resource without conflict.
Semaphores are integer variables that are used to solve the critical section problem. They are a
fundamental synchronization system that enables simultaneous cycle execution while preventing
information race and halt situations.
Semaphores are a popular mechanism for synchronizing tasks. A semaphore can be thought of as
an event counter which can never become negative. A program can use any number of semaphores.
Semaphore is just like this Key and the bike is the shared resource. Whenever a task wants access
to the shared resource, it must acquire the semaphore first. The task should release the semaphore
after it is done with the shared resource. Till this time all other tasks have to wait if they need
access to shared resource as semaphore is not available. Even if the task trying to acquire the
semaphore is of higher priority than the task acquiring the semaphore, it will be in wait state until
semaphore is released by the lower priority task.

Types of Semaphore:-
 Binary Semaphore: Here, there are only two values of Semaphore in Binary Semaphore Concept.
The two values are 1 and 0. 1 Process has capability to enter critical section area.
0  Process does not have the capability to enter the critical section area.
 Counting Semaphore: Here, there are two sets of values of Semaphore in Counting Semaphore
Concept. The two types of values are values greater than and equal to one and other type is value
equal to zero. If the Value of Binary Semaphore is greater than or equal to 1, then the process has
the capability to enter the critical section area. If the value of Binary Semaphore is 0 then the
process does not have the capability to enter the critical section area.

Code:
#include<stdio.h>
void main()
{
int buffer[10], bufsize, in, out, produce, consume, choice=0;
in = 0;
out = 0;
bufsize = 2;
while(choice !=3)
{
printf("\n1. Produce \t 2. Consume \t3. Exit");
printf("\nEnter your choice: ");
scanf("%d", &choice);
switch(choice)
{
case 1:
if((in+1)%bufsize==out)
printf("\nBuffer is Full");
else
{
printf("\nEnter the value: ");
Kadaganchi, Aland Road, Kalaburagi 585 367, Karnataka, India.
Website: www.cuk.ac.in
Central University of Karnataka
Dept.: ECE Dept.

(Established by an Act of the Parliament in 2009) Curriculum

School of Engineering
Syllabus Contents

w.e.f. 2024-25
scanf("%d", &produce);
buffer[in] = produce;
in = (in+1)%bufsize;
}
break;
case 2:
if(in == out)
printf("\nBuffer is Empty");
else
{
consume = buffer[out];
printf("\nThe consumed value is %d", consume);
out = (out+1)%bufsize;
}
break;
}
}
}

Output:

Kadaganchi, Aland Road, Kalaburagi 585 367, Karnataka, India.


Website: www.cuk.ac.in
Central University of Karnataka
Dept.: ECE Dept.

(Established by an Act of the Parliament in 2009) Curriculum

School of Engineering
Syllabus Contents

w.e.f. 2024-25

9. Bankers Algorithm for Deadlock Avoidance


A deadlock-avoidance algorithm in an operating system (OS) examines the resource-allocation state
to ensure that a circular-wait condition can't exist. The resource-allocation state is defined by the
number of available and allocated resources, and the maximum demands of the processes.
To prevent deadlock, operating systems use the Banker's algorithm or the resource allocation graph.
The Banker's algorithm is a resource allocation and deadlock avoidance algorithm developed by
Edsger Dijkstra. It prevents a single thread from entering the same lock more than once.
The algorithm works by:-
 Simulating the allocation of predetermined maximum possible amounts of all resources
 Making an "s-state" check to test for possible deadlock conditions for all other pending
 Using a "need matrix" to represent the resources that each process still needs to complete its
execution
 Checking if there is enough available resources to satisfy the request
 Checking if granting the request will still result in a safe state

To prevent the hold and wait condition, processes must be prevented from holding one or more
resources while simultaneously waiting for one or more others. One possibility for this is to require
that all processes request all resources at one time.

Banker’s Algorithm:-
1. Initialize the system
2. Define a request
3. Check if the request can be granted
4. Check if the system is in a safe state
5. Release the Resources

Kadaganchi, Aland Road, Kalaburagi 585 367, Karnataka, India.


Website: www.cuk.ac.in
Central University of Karnataka
Dept.: ECE Dept.

(Established by an Act of the Parliament in 2009) Curriculum

School of Engineering
Syllabus Contents

w.e.f. 2024-25

Code:
#include<stdio.h>
struct file
{
int all[10];
int max[10];
int need[10];
int flag;
};
void main()
{
struct file f[10];
int fl;
int i, j, k, p, b, n, r, g, cnt=0, id, newr;
int avail[10],seq[10];
printf("Enter number of processes -- ");
scanf("%d",&n);
printf("Enter number of resources -- ");
scanf("%d",&r);
for(i=0;i<n;i++)
{
printf("Enter details for P%d",i);
printf("\nEnter allocation\t -- \t");
for(j=0;j<r;j++)
scanf("%d",&f[i].all[j]);
printf("Enter Max\t\t -- \t");
for(j=0;j<r;j++)
scanf("%d",&f[i].max[j]);
f[i].flag=0;
}
printf("\nEnter Available Resources\t -- \t");
for(i=0;i<r;i++)
scanf("%d",&avail[i]);
printf("\nEnter New Request Details -- ");
printf("\nEnter pid \t -- \t");
scanf("%d",&id);
printf("Enter Request for Resources \t -- \t");
for(i=0;i<r;i++)
{
scanf("%d",&newr);
f[id].all[i] += newr;
avail[i]=avail[i] - newr;
}
for(i=0;i<n;i++)
{
for(j=0;j<r;j++)
Kadaganchi, Aland Road, Kalaburagi 585 367, Karnataka, India.
Website: www.cuk.ac.in
Central University of Karnataka
Dept.: ECE Dept.

(Established by an Act of the Parliament in 2009) Curriculum

School of Engineering
Syllabus Contents

w.e.f. 2024-25
{
f[i].need[j]=f[i].max[j]-f[i].all[j];
if(f[i].need[j]<0)
f[i].need[j]=0;
}
}
cnt=0;
fl=0;
while(cnt!=n)
{
g=0;
for(j=0;j<n;j++)
{
if(f[j].flag==0)
{
b=0;
for(p=0;p<r;p++)
{
if(avail[p]>=f[j].need[p])
b=b+1;
else
b=b-1;
}
if(b==r)
{
printf("\nP%d is visited",j);
seq[fl++]=j;
f[j].flag=1;
for(k=0;k<r;k++)
avail[k]=avail[k]+f[j].all[k];
cnt=cnt+1;
printf("(");
for(k=0;k<r;k++)
printf("%3d",avail[k]);
printf(")"); g=1;
}
}
}
if(g==0)
{
printf("\n REQUEST NOT GRANTED -- DEADLOCK OCCURRED");
printf("\n SYSTEM IS IN UNSAFE STATE");
goto y;
}
}
printf("\nSYSTEM IS IN SAFE STATE");
printf("\nThe Safe Sequence is -- (");
Kadaganchi, Aland Road, Kalaburagi 585 367, Karnataka, India.
Website: www.cuk.ac.in
Central University of Karnataka
Dept.: ECE Dept.

(Established by an Act of the Parliament in 2009) Curriculum

School of Engineering
Syllabus Contents

w.e.f. 2024-25
for(i=0;i<fl;i++)
printf("P%d ",seq[i]);
printf(")");
y: printf("\nProcess\t\tAllocation\t\tMax\t\t\tNeed\n");
for(i=0;i<n;i++)
{
printf("P%d\t",i);
for(j=0;j<r;j++)
printf("%6d",f[i].all[j]);
for(j=0;j<r;j++)
printf("%6d",f[i].max[j]);
for(j=0;j<r;j++)
printf("%6d",f[i].need[j]);
printf("\n");
}
}

Output:

Kadaganchi, Aland Road, Kalaburagi 585 367, Karnataka, India.


Website: www.cuk.ac.in
Central University of Karnataka
Dept.: ECE Dept.

(Established by an Act of the Parliament in 2009) Curriculum

School of Engineering
Syllabus Contents

w.e.f. 2024-25
10. Simulate the concept of Dining Philosophers Problem
The dining philosophers problem was introduced by Dijkstra. Five philosophers live in a house,
where a table is laid for them. The life of each philosopher consists principally of thinking and
eating, and through years of thought, all of the philosophers had agreed that the only food that
contributed to their thinking efforts was spaghetti. Due to a lack of manual skill, each
philosopher requires two forks to eat spaghetti.
The eating arrangements are simple: a round table on which is set a large serving bowl of
spaghetti, five plates, one for each philosopher, and five forks. A philosopher wishing to eat goes
to his or her assigned place at the table and, using the two forks on either side of the plate, takes
and eats some spaghetti.
The problem: devise a ritual (algorithm) that will allow the philosophers to eat. The algorithm
must satisfy mutual exclusion (no two philosophers can use the same fork at the same time)
while avoiding deadlock and starvation. This problem may not seem important or relevant in
itself. However, it does illustrate basic problems in deadlock and starvation. Furthermore,
attempts to develop solutions reveal many of the difficulties in concurrent programming. In
addition, the dining philosophers problem can be seen as representative of problems dealing with
the coordination of shared resources, which may occur when an application includes concurrent
threads of execution. Accordingly, this problem is a standard test case for evaluating approaches
to synchronization.

Kadaganchi, Aland Road, Kalaburagi 585 367, Karnataka, India.


Website: www.cuk.ac.in
Central University of Karnataka
Dept.: ECE Dept.

(Established by an Act of the Parliament in 2009) Curriculum

School of Engineering
Syllabus Contents

w.e.f. 2024-25

Code:
int tph, philname[20], status[20], howhung, hu[20], cho;
main()
{
int i;
printf("\n\nDINING PHILOSOPHER PROBLEM");
printf("\nEnter the total no. of philosophers: ");
scanf("%d",&tph);
for(i=0;i<tph;i++)
{
philname[i] = (i+1);
status[i]=1;
}
printf("How many are hungry : ");
scanf("%d", &howhung);
if(howhung==tph)
{
printf("\nAll are hungry..\nDead lock stage will occur");
printf("\nExiting..");
}
else
{
for(i=0;i<howhung;i++)
{
printf("Enter philosopher %d position: ",(i+1)); scanf("%d", &hu[i]);
status[hu[i]]=2;
}
do
{
printf("1.One can eat at a time\t2.Two can eat at a time\t3.Exit\nEnter your choice:");
scanf("%d", &cho);
switch(cho)
{
case 1: one();
break;
case 2: two();
break;
case 3: exit(0);
default:
printf("\nInvalid option..");
}
}
while(1);
}
}

Kadaganchi, Aland Road, Kalaburagi 585 367, Karnataka, India.


Website: www.cuk.ac.in
Central University of Karnataka
Dept.: ECE Dept.

(Established by an Act of the Parliament in 2009) Curriculum

School of Engineering
Syllabus Contents

w.e.f. 2024-25
one()
{
int pos=0, x, i;
printf("\nAllow one philosopher to eat at any time\n");
for(i=0;i<howhung; i++, pos++)
{
printf("\nP %d is granted to eat", philname[hu[pos]]);
for(x=pos;x<howhung;x++)
printf("\nP %d is waiting", philname[hu[x]]);
}
}
two()
{
int i, j, s=0, t, r, x;
printf("\n Allow two philosophers to eat at same time\n");
for(i=0;i<howhung;i++)
{
for(j=i+1;j<howhung;j++)
{
if(abs(hu[i]-hu[j])>=1&& abs(hu[i]-hu[j])!=4)
{
printf("\n\ncombination %d \n", (s+1));
t=hu[i];
r=hu[j];
s++;
printf("\nP %d and P %d are granted to eat", philname[hu[i]],philname[hu[j]]);
for(x=0;x<howhung;x++)
{
if((hu[x]!=t)&&(hu[x]!=r))
printf("\nP %d is waiting", philname[hu[x]]);
}
}
}
}
}

Kadaganchi, Aland Road, Kalaburagi 585 367, Karnataka, India.


Website: www.cuk.ac.in
Central University of Karnataka
Dept.: ECE Dept.

(Established by an Act of the Parliament in 2009) Curriculum

School of Engineering
Syllabus Contents

w.e.f. 2024-25

Output:

Kadaganchi, Aland Road, Kalaburagi 585 367, Karnataka, India.


Website: www.cuk.ac.in

You might also like