CS3000 Operating Systems Course Overview
CS3000 Operating Systems Course Overview
Lecture – 1
(Course Overview)
2
Course Administration (3000)
• Prior knowledge: C, Data Structures, Computer Organization and Design
• Lecture slides will be available on moodle after lecture.
• Some reading material will be provided before/after the lecture.
• Discussion Time: Anytime except when we have class or laboratory (prior email is preferable).
• Lab: Once a week (Good Learning Experience).
• Easiest way to get a good grade in CS3000 is to pay attention in the class.
• 85% attendance is mandatory.
• Total = 42 Lectures, 14 Tutorials
Time Table
CS3000 Monday –11:00 AM – 11:50 AM
Tues – 8:00 AM – 8:50 AM
L T P Credits Wed – 12:00 PM – 12:50 PM
Thurs – 09:00 AM – 09:50 AM
3 1 0 4
3
Books & Reference Materials
1. Operating System Concepts,
8th Edition by Silberschatz
[Link].
2. Operating Systems: Internals
and Design Principles, 8th
Edition by William Stallings
3. Online Resources
4
Why Operating Systems Required?
Coordinate
Color
0
Fetch
5
Goal of OS
User - 1 User - 2 User - n
Computer Hardware
Goals
1 – Convenient to Use / User Friendly
2 – Efficiency
6
Usages of Operating System
Portable
resources
8
Operating System Market Share
Source:StatCounter
9
Types of OS (Types of Applications)
• Desktops • Mac OS, Windows, Ubuntu
• Servers • Windows Server, Redhat
• Embedded OS • Contiki OS
• Mobile OS • Android, iOS
• RTOS • RTLinux
• Secure Environment • SeLinux
10
Course Contents
• Structure of Operating System
• Functionalities & Services of an Operating System
Process Concept - System Calls & Management
Process Synchronization
Process Scheduling
Deadlock
Memory Management
I/O Management
11
Types of OS Every Job or Task has -
CPU Time
• Batch OS IO Time
• Transistors
• Starts another job only after the present job is completed entirely
• both CPU and IO Parts to be completed
• Poor CPU Utilization
• Low Throughput (Efficiency Aspect)
No of Jobs or Tasks completed
per unit time
12
• Stored Program Architecture
• Multiple Programs or Jobs are allowed
to be in Main Memory
13
Types of OS
• Multi Programming OS
• Overlapped execution of CPU and IO Operations Tasks
• When CPU is idle, switch to other Job
• Better CPU Utilization – when J1 is busy on IO; J2’s CPU part is
allowed
• Betters Throughput
• J1-IO J2-IO
14
Types of OS
• Multi Tasking OS
• Based on the concept of Time Sharing (= 2sec)
• Time Sliced Execution of Tasks
• Illusion of Simultaneous Execution of Tasks
J1 – 4 Sec
J2 – 3 Sec J1 J2 J3 J1 J3 J2 J3
J3 – 7 Sec
0 2 4 6 8 10 11 14
15
Types of OS
• Multi Processing OS
• More than 1 Processor
• Modern day Multicore Systems
• True Simultaneous or Parallel Processing
• High Throughput
• High Reliability – Fault Tolerant Systems
• Economical – from a user and application management view
Processor - 1 J1 J2 J3 J1 J3 J2 J3
Processor - 2 J4 J5 J6 J5 J6 J4
16
Functionalities or Services of OS
Storage Management
Process Management Operating
System File Mamagement
Process Creation, execution, Creation, deletion of files and
termination directories
Process Scheduling Manipulation of files and
Interprocess Communication directories
Thread-Scheduling Mapping files onto secondary
Synchronization of processes storage
Handling Deadlocks
Mass-Storage Management
Memory Management Free Space Management
Storage Allocation
• Keeping track of used and free
Disk Scheduling
space
• Deciding which processes and
data to move into and out of Protection and Security
memory
• Allocating and deallocating • Ensuring control access of resources
memory space
Operating Systems
(CS-3000)
Lecture-2
I/O Completion
I/O Request
Suspend
Resume
Block/
Wait
Suspend Suspend
Ready
Resume
14
• New: Newly Created Process (or) being-created process.
• In this step, the process is about to be created but not yet created, it is the
program which is present in secondary memory that will be picked up by OS to
create the process.
• Ready: After creation process moves to Ready state, i.e. the process is ready for
execution.
• New -> Ready to run. After the creation of a process, the process enters the
ready state i.e. the process is loaded into the main memory. The process here
is ready to run and is waiting to get the CPU time for its execution. Processes
that are ready for execution by the CPU are maintained in a queue for ready
processes called READY QUEUE.
• Running: Currently running process in CPU (only one process at a time can be
under execution in a single processor).
• The process is chosen by CPU for execution and the instructions within the
process are executed by any one of the available CPU cores.
• Wait (or Blocked): When a process requests I/O access.
• Whenever the process requests access to I/O or needs input from the user or
needs access to a critical region (the lock for which is already acquired) it
enters the blocked or wait state. The process continues to wait in the main
memory and does not require CPU. Once the I/O operation is completed the
process goes to the ready state.
• Complete (or Terminated): The process completed its execution. Process
is killed as well as PCB is deleted.
• Suspend Ready: When the ready queue becomes full(that means no
sufficient memory is available for new process), then some processes are
moved to suspend ready state to give space at RAM for new high priority
process
• Process that was initially in the ready state but were swapped out of
main memory and placed onto external storage by scheduler are said to
be in suspend ready state.
• The process will transition back to ready state whenever the process is
again brought onto the main memory.
• Suspend Block: When all processes is in waiting queue, then some of the
waiting processes are moved to suspended block to give space at RAM
for new processes or high priority process
• Similar to suspend ready but remove the process which was waiting to
perform I/O operation
• When work is finished it may go to suspend ready or blocked state
Process Scheduling Queues
• Three
• Job queue – set of all processes in the system which are ready to
come to main memory, maintain in secondary memory
• Ready queue – set of all processes residing in main memory, ready
and waiting to execute in processor, maintain in main memory
• Device queues – set of processes waiting for an I/O device, maintain
in main memory
• Suspend block and suspend ready queue is maintained in secondary
memory
I/O Completion
I/O Request
Suspend
Resume
Block/
Wait MTS
MTS
Suspend Suspend
Ready
Resume
22
Context Switching
• The process of saving the context of one process and loading the
context of another process.
• When process moves from running to block state for I/O operation
• When process moves from running to terminate (no need to save state of
running process, but need to load state of new process from ready to running)
Operating Systems
(CS-3000)
Lecture-3
• Preemptive
• SRT
• RR
• Priority
Different Time based Parameters w.r.t.
Process
• Arrival Time (AT) - Time the Process comes to the Ready State
• Burst Time (BT) – Execution time of the process – also referred as Service Time
• Completion Time (CT) – Time at which process completes its execution.
• Turn Around Time (TAT) - Time required for an application (process) to give an
output to the end user
• TAT = CT - AT
• Waiting Time (WT) - Time Difference between turn around time and burst time.
• WT = TAT – BT
• Response Time – Time for the System to Respond to Process or User (First
Response time on System Clock)
• Time Since the Request is Submitted (AT) and the First Response Time
FCFS
PID/P# AT BT CT/FT TAT WT
1 0 7 4 4 0
2 2 4 7 6 3
3 4 2 8 6 5
4 7 1 10 7 5
15 11 6
Average WT 19/5
GANTT CHART
11
FCFS
PID/P# AT BT CT/FT TAT WT
1 0 7 4 4 0
2 0 4 7 6 3
3 0 2 8 6 5
4 0 5 10 7 5
15 11 6
Average WT 19/5
GANTT CHART
13
Advantages and Disadvantages
• Advantages
• Simple
• Fair
• Disadvantages
• Waiting time depends on arrival order
• Convoy effect
SJF
PID/P# AT BT CT/FT TAT WT
1 0 7 4 4 0
2 0 4 7 6 3
3 0 2 8 6 5
4 0 5 10 7 5
15 11 6
Average WT 19/5
GANTT CHART
16
SJF
PID/P# AT BT CT/FT TAT WT
1 0 7 4 4 0
2 2 4 7 6 3
3 4 2 8 6 5
4 7 1 10 7 5
15 11 6
Average WT 19/5
GANTT CHART
18
Advantages and Disadvantages
• Advantages
• Optimal: Min avg. waiting time and response time
• Disadvantages
• Difficult to predict burst time
• Starvation
Priority based Non-Preemptive Scheduling
PID/P# Priority AT BT CT/FT TAT WT
1 3 0 7 4 4 0
2 2 0 4 7 6 3
3 1 0 2 8 6 5
4 4 0 5 10 7 5
15 11 6
Average WT 19/5
GANTT CHART
21
Operating System
(CS-206)
Lecture-4
Jaishree Mayank
Assistant Professor
IIITDM Kancheepuram
Preemptive Scheduling Algorithm
• SRTF
• RR
• Priority
Different Time based Parameters w.r.t.
Process
• Arrival Time (AT) - Time the Process comes to the Ready State
• Burst Time (BT) – Execution time of the process – also referred as
Service Time
• Completion Time (CT) – Time at which process completes its execution.
• Turn Around Time (TAT) - Time required for an application (process) to
give an output to the end user
• TAT = CT - AT
• Waiting Time (WT) - Time Difference between turn around time and
burst time.
• WT = TAT – BT
• Response Time – Time for the System to Respond to Process or User
(First Response time on System Clock)
• Time Since the Request is Submitted (AT) and the First Response Time
Shortest-First Job-With Preemption
SRTF-Shortest Remaining Time First
• If the new process arrives with a shorter burst than remaining of
current process then schedule a new process
• Reducing average waiting time and average response time
• Not Practical
SRTF
PID/P# AT BT CT/FT TAT WT
1 0 7 4 4 0
2 0 4 7 6 3
3 0 2 8 6 5
4 0 5 10 7 5
15 11 6
Average WT 19/5
GANTT CHART
5
SRTF
PID/P# AT BT CT/FT TAT WT
1 0 7 4 4 0
2 2 4 7 6 3
3 4 2 8 6 5
4 7 1 10 7 5
15 11 6
Average WT 19/5
7
Round-Robin Scheduling approach
• Each process gets a small unit of CPU time (time quantum), usually
10-100 milliseconds. After this time has elapsed, the process is
preempted and added to the end of the ready queue.
• If there are n processes in the ready queue and the time quantum is
q, then each process gets 1/n of the CPU time in chunks of at most q
time units at once. No process waits more than (n-1)q time units.
• Preemptive approach
• Performance
• q large FIFO
• q small q must be large with respect to context switch, otherwise overhead
is too high
RR
PID/P# AT BT CT/FT TAT WT
1 0 7 4 4 0
2 0 4 7 6 3
3 0 2 8 6 5
4 0 5 10 7 5
15 11 6
Average WT 19/5
GANTT CHART
9
RR
PID/P# AT BT CT/FT TAT WT
1 0 7 4 4 0
2 2 4 7 6 3
3 3 2 8 6 5
4 7 1 10 7 5
15 11 6
Average WT 19/5
GANTT CHART
12
Operating System
(CS-206)
Lecture-5
Jaishree Mayank
Assistant Professor
IIITDM Kancheepuram
FCFS
PID/P# AT BT CT/FT TAT WT
1 0 7 4 4 0
2 0 4 7 6 3
3 0 2 8 6 5
4 0 5 10 7 5
15 11 6
Average WT 19/5
GANTT CHART
2
FCFS
PID/P# AT BT CT/FT TAT WT
1 0 7 4 4 0
2 2 4 7 6 3
3 4 2 8 6 5
4 7 1 10 7 5
15 11 6
Average WT 19/5
4
RR
PID/P# AT BT CT/FT TAT WT
1 0 7 4 4 0
2 0 4 7 6 3
3 0 2 8 6 5
4 0 5 10 7 5
15 11 6
Average WT 19/5
GANTT CHART
6
RR
PID/P# AT BT CT/FT TAT WT
1 0 7 4 4 0
2 2 4 7 6 3
3 4 2 8 6 5
4 7 1 10 7 5
15 11 6
Average WT 19/5
8
Operating System
(CS-206)
Lecture-5
Jaishree Mayank
Assistant Professor
IIITDM Kancheepuram
HRRN-Non-preemptive
PID/P# AT BT CT/FT TAT WT
1 0 7 4 4 0
2 0 4 7 6 3
3 0 2 8 6 5
4 0 5 10 7 5
15 11 6
Average WT 19/5
GANTT CHART
3
HRRN
PID/P# AT BT CT/FT TAT WT
1 0 7 4 4 0
2 2 4 7 6 3
3 4 2 8 6 5
4 7 1 10 7 5
15 11 6
Average WT 19/5
5
Operating Systems (CS3000)
Lecture – 8
(Multilevel Scheduling)
5
Multilevel Queue Scheduling
• Higher priority System Processes
P10 P6 P12 P1
Interactive Processes
P11 P7 P3 P2
Batch Processes
P13 P14 P15
• Lower Priority
6
Multilevel Feedback Queue
• A process can move between the various queues processes
● Does not demand a knowledge of running time of jobs
●Balances both turnaround time (optimized by SJF/PSJF by selecting the
smallest job) and response time (optimized by RR by alternating)
• Multilevel feedback queue defined by the following parameters
• Numbers of queues
• Scheduling algorithm for each queue
• Methods used to determine when to upgrade a process
• Methods used to determine when to demote a process
• Methods used to determine which queue a process will enter when a
process needs services
7
Multilevel Feedback Queue
● Rule 1: If Priority(A) > Priority(B), A runs (B doesn’t)
● Rule 2: If Priority(A) = Priority(B), A & B run in RR
● Rule 3: When a job enters the system, it is placed at the highest priority (the
topmost queue)
● Rule 4a: If a job uses up an entire time slice while running, its priority is reduced
(i.e., it moves down one queue)
–Intuition – CPU-bound job
● Rule 4b: If a job gives up the CPU before the time slice is up, it stays at the same
priority level
–Intuition – I/O-bound (interactive job)
Multilevel Feedback Queue
• Example: Consider 3 queues
• Q0 - time quantum 8 milliseconds
• Q1 –time quantum 16 milliseconds
• Q2 – FCFS
• Scheduling:
• A new job enters queue Q0 which is served for 8 ms.
• When it gains CPU, job receives 8 milliseconds. If it does not finish in 8
milliseconds, job is moved to queue Q1
• At Q1 job is again served RR and receives 16 additional milliseconds. If it still
does not complete, it is preempted and moved to queue Q2.
• At Q2 it executes as FCFS
10
Multilevel Feedback Queue
Quantum=8
Quantum=16
FCFS
11
Queues during process execution
LTS STS
Job
Ready Queue CPU EXIT
Pool/
Queue
Waiting Queue 1
Waiting Queue n
12
Multilevel Feedback Queue
● Rule 1: If Priority(A) > Priority(B), A runs (B doesn’t)
● Rule 2: If Priority(A) = Priority(B), A & B run in RR
● Rule 3: When a job enters the system, it is placed at the highest priority (the
topmost queue)
● Rule 4a: If a job uses up an entire time slice while running, its priority is reduced
priority level
● Issues
–Trick the scheduler – I/O just before the time slice is over
–A program may change its behavior over time
Multilevel Feedback Queue
● Rule 1: If Priority(A) > Priority(B), A runs (B doesn’t)
● Rule 2: If Priority(A) = Priority(B), A & B run in RR
● Rule 3: When a job enters the system, it is placed at the highest priority (the
topmost queue)
● Rule 4: Once a job uses up its time allotment at a given level (regardless of how
many times it has given up the CPU), its priority is reduced (i.e., it moves down one
queue)
● Rule 5: After some time period S, move all the jobs in the system to the topmost
queue
Comparison b/w different scheduling approach
Algorithm Strategy Average waiting Preemption Starvation Performance
time
FCFS Acc. To arrival Large No NO Slow
time performance/con
voy effect
SJF lowest cpu burst Smaller than FCFS No Yes Mini Avg Waiting
time time
SRTF Same as SJF but Smaller than FCFS YES Yes Min avg waiting
preemption time
allowed
18
Multiple-Processor Systems
● Multiprocessor systems are increasingly commonplace
–In desktop machines, laptops, and even mobile devices
● Multicore processor
–Multiple CPU cores are packed onto a single chip
Multiple-Processor Scheduling - Challenges
● The same user program would not run faster
● CPU scheduling more complex when multiple CPUs are available –
where + when
–Where to run scheduler?
–Synchronization
● Shared data
Asymmetric Multiprocessing (Master-Slave)
● All scheduling decisions, I/O processing, and other system activities
handled by a single processor—the master
● The other processors execute the assigned program
● Only one processor accesses the system data structures, reducing the
need for data sharing
Asymmetric Multiprocessing - Issues
●Contention
–Slave processors waiting for Master to make Scheduling decisions
Symmetric Multiprocessing
● Each processor runs its own scheduler
Symmetric Multiprocessing
● Each processor runs its own scheduler
–Global queue: All processes in common ready queue
Symmetric Multiprocessing
● Each processor runs its own scheduler
–Global queue: All processes in common ready queue
–Advantages
●Good CPU utilization
–Issues
●Scalability – contention for global queue
● Load imbalance
Symmetric Multiprocessing
● Each processor runs its own scheduler
–Partitioned queue: per-processor a private queue
●Static partitioning of processes
–Advantages
●Easy to implement – no need of synchronization
●Scalable
–Issues
●Load imbalance
●Solution??
Symmetric Multiprocessing
● Each processor runs its own scheduler
–Hybrid Approach: global queue + partitioned queue
Lecture – 8
Code
0
Memory Map of Process
5
Communicating with the OS (System Calls)
• System Calls are a set of special functions which the OS
supports.
• Why?
• to get information
• to access hardware/ resources within the Kernel.
6
printf( )
int x = 30;
printf(“%d”, x); write System Call 30
implementation
call Library
present in libc
write(STDOUT) TRAP
Handler
TRAP
RETURN
7
What Happens During System Calls?
• process (user mode) process (kernel mode)
• allow the kernel or the operating system to actually execute the task
8
Function Call v/s System Call
• CALL instruction • TRAP instruction
• User Space • User Space Kernel Space
• CALL jumps to a relocatable • TRAP jumps to a fixed
address address
9
System Calls for Files
• Files: Data remains even if power is off
• Operations on Files:
• open()
• close()
• read()
• write()
• Files are stored in HDD. System call required to access
Hardware.
• Process -> System Call -> Kernel -> HDD -> Return FP to
Process
12
Monolithic OS Structure
user processes access functionalities
within each modules
13
Microlithic OS Structure
user processes access functionalities
within each modules
14
What Metadata of a Process Kernel Stores?
• PCB
• Kernel Stack for User Process Kernel/OS
• During System Calls
Kernel Stack
• Page Table for that User Process
Stack
Heap
Data
Code
15
Operating Systems (CS3000)
Lecture – 11
(fork() System Call)
2
What Metadata of a Process Kernel Stores?
• PCB
• Kernel Stack for User Process Kernel/OS
• During System Calls
Kernel Stack
• Page Table for that User Process
Stack
Heap
Data
Code
3
Creating a Process by Cloning
• fork()
• Child Process is duplicate of parent process
• PID Parent process is Child’s PID
• PID Child process is 0
Parent
Process-1
4
fork( )
{ { {
pid_t pid; pid_t pid; pid_t pid;
pid=fork();
8
Operating Systems (CS3000)
Lecture – 12
(exec(), wait() System Call)
Parent
Process-1
2
3
The classic fork( ) Bomb!
• Overall 8 processes in Main Memory as indicated at the leaf level
nodes count
• In general n fork class (non conditional) will result in
________processes
int main()
{
fork();
fork();
fork();
printf(“Magic of fork()\n”);
return 0;
}
4
5
How to create a new definition of process?
• So far fork example we did, child process carried the same image as
the parent process.
• Practicality requires child to have new definition.
• Is it possible?
• Yes
6
exec( ) system call
• fork() system call is used to create a SEPARATE, DUPLICATE process with
non-shared pages from which process (parent) it is called.
• Using Copy-on-Write (COW)-SEPARATE, DUPLICATE process with Shared
pages
• The new child process will have different PID.
• When exec() system call is invoked from (p1), the program specified in the
parameters of exec() will replace the entire process.
• exec() takes one parameter, which is another program(p2)
• p1 will be replaced by p2.
• Replace one process with another process (PID don’t change)
• As we are not creating new process
• We are replacing an existing one
• Same PID with different content
7
8
9
wait( ) system call
• called in parent process
• int wait(arg);
• Parent goes to block state
• Until one of it’s children terminates
• -1: if no child is executing or exists
• When the child process exits i.e exit(0), it would cause the parent process to
wake up
• the wait function returns the child process’s pid
• The parent waits for the child process using this system call.
10
Why wait( ) system call ?
11
Operating Systems (CS3000)
Lecture – 13
(exit() System Call, Zombie, Orphan, Reaper
Processes)
2
exit( ) system call
• called in child process
• Results in process termination
• Return status is passed to the parent (Voluntary Termination)
• Forcefully termination
• kill() system call
3
Process system calls Possible Flow
Parent Parent
wait() Continue
Parent
fork()
child child
exec() exit()
4
Orphan Process
• When a parent process terminates before its child
• The first process will adopt the orphan child.
5
Operating Systems (CS3000)
Lecture – 12
(Inter Process Communication)
5
IPC
• Reasons for cooperating processes:
– Computation speedup
●
Multiple processing cores
●
Distributed computing
• Modularity
– Subtasks into separate processes or threads
• Client-Server Computing
6
IPC
3 Ways
• Shared Memory
• Message Passing
• Pipes
• Signals
7
Shared Memory RAM
• Process1
• Create SM Kernel/OS
• Attach SM to it’s address Space
• Process 2 Read SM
• Attach SM to it’s address Space
Process - 2
• Read Data from SM written by
Writer
8
9
Functions used in SM
• shmget() to Create the SM
• shmat() to attach the SM with the address space of the process
• shmdt() to detach the SM
• shmctl() to Destroy the SM
10
shmget()
• int shmget(key_t key, size_t size, int shmflg);
• #include<sys/ipc.h>
• #include<sys/shm.h>
11
shmat()
• void* shmat(int shmid, const void * shmaddr, int shmflg);
• shmid -> value returned by shmget().
• shmaddr -> where to attach the SM in the address space of the
calling function
• Address not know so write NULL. If shmaddr is a NULL pointer, the segment
is attached at the first available address as selected by the system.
• OS will assign it at a suitable location.
• shmflg -> if shmaddr is NULL, shmflg is 0.
• Incase of Unsuccessful -> Returns -1
• #include<sys/types.h>
• #include<sys/shm.h>
12
shmdt()
13
shmctl()
• int shmctl(int shmid, int command, struct shmid_ds *buf);
• returns information about a shared memory segment and can modify it
• shmid -> value returned by shmget().
• IPC_STAT: Retrieve the status of the shared memory segment.
• IPC_SET: Set the status of the shared memory segment.
• IPC_RMID: Remove the shared memory segment.
• This is a pointer to a struct shmid_ds structure that is used to get or set
information about the shared memory segment
• On success, it returns 0, on failure, –1
14
Server.c
server.c
15
client.c
16
Operating Systems (CS3000)
Lecture – 16
(Inter Process Communication - 2)
Write
Pipe
Read
2
Creating Pipe between Parent and Child process
• int pipe(int pipefd[2]);
• a file descriptor is used to access the two ends of the pipe: one end
for reading and one end for writing
5
Message Passing using Pipes
• ssize_t read(int fd, void *buf, size_t count)
6
Message Passing using Pipes
• ssize_t write(int fd, void *buf, size_t count)
The file descriptor to write to.
A pointer to a buffer where the write data will be stored.
The maximum number of bytes to write.
• Return the number of bytes written
• Return zero in case nothing is written
• Return -1 in case of failure
7
Message Passing using Pipes
• _int close(int fd)
Closing the pipe end.
8
Message Passing using Pipes
• Algorithm
• Step 1 − Create a pipe
• Step 2 − Create a child process
• Step 3 − Parent process writes to the pipe
• Step 4 − Child process retrieves the message from the pipe and
writes it to the standard output
• Step 5 − Repeat step 3 and step 4 once again
9
Two-way Communication Using Pipes
• If both the parent and the child needs to write and read from the
pipes simultaneously
• Two pipes are required
10
Two-way Communication Using Pipes
• Algorithm
• Step 1 − Create pipe1 for the parent process to write and the child
process to read
• Step 2 − Create pipe2 for the child process to write and the parent
process to read
• Step 3 − Close the unwanted ends of the pipe from the parent and
child side
• Step 4 − Parent process to write a message and child process to
read and display on the screen
• Step 5 − Child process to write a message and parent process to
read and display on the screen
11
Pipe1.c
12
Pipe2.c
13
Operating Systems (CS3000)
Lecture – 15
(Inter Process Communication - 2)
2
Message Passing RAM
• SM is created in Kernel
SM
• System calls are used Kernel/OS
• send(): Write to SM send ()
• receive(): Read from SM
Process - 1 receive()
Process - 2
3
IPC using Message Queues
• linked list of messages
• stored within the kernel
• identified by a message queue identifier.
• Functions
• msgget() To create a message queue/Open Existing
• msgsnd() To write message to message queue by Sender/New messages
are added to the end of the queue
• msgrcv() To retrieve message from message queue by Receiver
• msgctl() The control function
4
IPC using Message Queues
• Sender
• Create the MQ
• Add data to the MQ
• Receiver
• Retrieve the data from MQ
• Delete the MQ
5
IPC using Message Queues
• int msgget(key_t key, int msgflg);
6
IPC using Message Queues
• The *msgp parameter points to a user-defined buffer that must contain the
following:
• A field of type long int that specifies the type of the message.
• An array that contains the actual content of the message.
7
IPC using Message Queues
• int msgsnd(int msqid, void *msgp, size_t msgsz, int msgflg);
• The following structure is an example of what the user-defined buffer might
look like for a message that has 5 bytes of data.
struct mymsg
{
long int mtype; /* message type */
char mtext[5]; /* message text */
}
• The value of mtype must be greater than zero. When messages are received
with msgrcv(), the message type can be used to select the messages.
• The message data can be any length up to the system limit.
8
IPC using Message Queues
• int msgsnd(int msqid, void *msgp, size_t msgsz, int msgflg);
•
• msgsz: Length of the data part of the message to be sent.
• msgflg: If the message queue is full, the msgflg parameter specifies the
action to be taken. The actions are as follows:
• 0: Suspended
• IPC_NOWAIT: do not wait for space to become available on the message queue and
return immediately.
9
IPC using Message Queues
• int msgrcv(int msqid, void *msgp, size_t msgsz, long int msgtyp, int
msgflg);
The msgrcv() function reads a message from the message queue
specified by the msqid parameter and places it in the user-defined
buffer pointed to by the *msgp parameter.
The *msgp parameter points to a user-defined buffer that must
contain the following:
• A field of type long int that specifies the type of the message.
• A data part that contains the data bytes of the message.
10
IPC using Message Queues
• int msgrcv(int msqid, void *msgp, size_t msgsz, long int msgtyp, int
msgflg);
struct mymsg
{
long int mtype; /* message type */
char mtext[5]; /* message text */
}
• The value of mtype is the type of the received message, as specified
by the sender of the message.
• The msgsz parameter specifies the size in bytes of the data part of
the message.
• The received message is truncated to msgsz bytes if it is larger than msgsz.
11
IPC using Message Queues
• int msgrcv(int msqid, void *msgp, size_t msgsz, long int msgtyp, int
msgflg);
12
IPC using Message Queues
• int msgrcv(int msqid, void *msgp, size_t msgsz, long int msgtyp, int
msgflg);
• If a message of the desired type is not available on the message queue,
the msgflg parameter specifies the action to be taken. The actions are as
follows:
13
IPC using Message Queues
• int msgctl(int msqid, int cmd, struct msqid_ds *buf);
• The msgctl() function allows the caller to control the message queue
specified by the msqid parameter.
• msqid Message queue identifier, a positive integer. It is returned by
the msgget() function and used to identify the message queue on which to
perform the control operation.
• cmd Command, the control operation to perform on the message queue.
• buf Pointer to the message queue data structure to be used to get or set
message queue information.
• msqid_ds
14
MQ_Send1.c
15
MQ_Send1.c
16
Operating Systems (CS3000)
Lecture – 17
(Inter Process Communication - 4)
2
Signals
• What Process will do on receipt of Signal?
• Will stop what its doing and take some action
3
Signals
• How to raise a signal?
• Program
• System generated
• What happens?
• Default defined action
• Doesn’t want default?
• User defined action/ handling of signal
• Ignore Signal?
• Yes
• SIGSTOP/SIGKILL
4
Signal handling
• On Signal receipt, the process has a choice of action.
• The process can ignore the signal – Signal is discarded
• Can specify a handler function
• Accept the default action for the specific kind of signal
• If the signal has not been neither handled nor ignored, its default
action takes place.
5
Signal handling
int signal (int signum, void (*func)(int))
#include<stdio.h>
#include<signal.h>
int main()
{
signal(SIGUSR1,sig_handler);
printf(“I am in main()\n");
raise(SIGUSR1);
printf(“I am in main() again\n");
return 0;
}
6
Signal handling
• int sigaction(int signum, const struct sigaction *act, struct sigaction
*oldact)
• To change the signal action
7
Operating Systems (CS3000)
Lecture – 16
(Inter Process Communication - 5)
2
To create a Named pipe
• int mknod(const char *pathname, mode_t mode, dev_t dev);
• create a special file or file system node such as ordinary file, device file,
or FIFO.
• The pathname either absolute path or relative path of the file.
• The mode specified is the mode of file which specifies the file type and
the file permission.
• The dev field is to specify device information such as major and minor
device numbers (Default 0).
• return zero on success and -1 in case of failure.
3
Message Passing using Pipes
int mkfifo(const char *pathname, mode_t mode)
4
Message Passing using Named Pipes (FIFO)
•Algorithm: server process.
STEP1: Creates a named pipe (using library function mkfifo()) with name
“fifofile” in directory, if not created. (Only one procees will create the pipe)
STEP2: Opens the named pipe for read purpose.
STEP3: Waits infinitely for a message from the client.
STEP4: Print message received from the client and close the file.
STEP5: Opens the named pipe for write purpose.
STEP6: Accepts string from the user.
STEP7: Sends a message to the client and close the named pipe.
STEP8: Repeats infinitely until the user enters the string “end”.
5
Message Passing using Named Pipes
• Algorithm: Client process
6
Pipe2.c
7
8
Operating Systems (CS3000)
(Threads-Part1)
Process
P1 P2 P3 P4
Processors
Motivation – Speedup with Multiple Process
10000000/4=2.5 million
• Create 4 processes, each loop does 1/4th of
the work.
• Properties
Process1 Process2 Process3 Process4
• Create 4 processes using fork system call
• Each process is isolated from each other
• IPC mechanish-more system calls
• Process management system calls
• Each process has own memory map
• Instructions
• Data
• Stack
P1 P2 P3 P4 • heap
•
Processors
Motivation
• Problems on Creating 4 Processes
• Overhead
• due to considerable amount of system call.
• due to large portion of these processes are similar
• Threads in the process are not isolated from registers registers registers
each other.
stack stack stack
• Each thread state /thread control block /thread
execution context contains
• Thread id
• Program counter
• Registers
• Stack
Advantages of Threads over Processes
• Lightweight
• Efficient communication between entities
• Efficient context switching
Thread vs Processes
• A thread has no data segment or • A process has code, heap, stack
heap and other segments.
• A thread cannot live its own. It • We can consider a process has
needs to be attached to a at-least one thread.
process.
• There can be more than one • Processes doesn’t share the
thread in a process. Each thread files.
has its own stack.
• If a process dies, all threads die.
• If a thread dies, its stack is
reclaimed.
How to create and manage threads?
• Destroy a thread
• void pthread_exit (void *retval);
• pass a pointer to the return value, in order to pass the return status of the
thread
• Join:- wait for a specific thread to complete
• int pthread_join (pthread_t thread, void **retval);
• the parent thread will wait for it to complete by calling the pthread_join()
function.
pthread library 0+1+2 + … + 99 = 4950
#include <pthread.h> int main(){
#include <stdio.h> pthread_t t1, t2, t3, t4;
int sum[4];
pthread_create(&t1, NULL, thread_fn, (void *)0);
void *thread_fn (void *arg) pthread_create(&t2, NULL, thread_fn, (void *)1);
{ pthread_create(&t3, NULL, thread_fn, (void *)2);
int id =(int) arg;
pthread_create(&t4, NULL, thread_fn, (void *)3);
int start =id*25;
int i=0;
pthread_join(t1, NULL);
while(i<25) pthread_join(t2, NULL);
{
pthread_join(t3, NULL);
sum[id]+=(i+start);
pthread_join(t4, NULL);
i++;
} printf(“%d\n”, sum[0]+sum[1]+sum[2]+sum[3]);
return NULL; return 0;
}
}
Operating Systems (CS3000)
Lecture – 34
(Threads - 2)
Agenda
• We will understand how the thread are managed.
Who manages Thread?
• There are two Strategies
28
Operating Systems (CS3000)
Lecture – 21
(Threads - Scheduling)
• Scheduler Activation:
Scheme for communicating between the user thread-library and the kernel.
Thread Scheduling
Process contention Scope (PCS):
Competition for the CPU takes place among threads belonging to the same
process.
The thread library schedules user-level threads to run on an available LWP.
Apply for many-to many and many-to-one model
PCS is done according to priority
User-level thread priorities are set by the programmer and are not
adjusted by the thread library, although
some thread libraries may allow the programmer to change the priority of
a thread.
Thread Scheduling
System Contention Scope (SCS):
Deciding kernel thread to schedule onto a CPU
Apply on one to one model
pthread Scheduling
PTHREAD_SCOPE_PROCESS: Schedules threads using PCS Scheduling
PTHREAD_SCOPE_SYSTEM: Schedules threads using SCS scheduling
Second parameter:
value of PTHREAD_SCOPE_PROCESS or
PTHREAD_SCOPE_PROCESS
pthread Scheduling
Second parameter: value of pointer to the int value that is set to the current
8
Operating Systems (CS3000)
Lecture – 20
(Process Synchronization - 1)
2
Why Synchronization?
{ {
--- ---
--- int counter = 5 ---
counter++; counter--;
---- ----
Shared Variable
---- ----
} }
Process - 1 Process - 2
• Output?
• 5 (Expected) P1 P2
P2 P1
3
Why Synchronization?
{ {
--- ---
--- int counter = 5 ---
counter++; counter--;
---- ----
Shared Variable
---- ----
} }
Process - 1 Process - 2
• Output?
•5
4
Why Synchronization?
{ {
--- ---
1. R1<- counter --- int counter = 5 --- 1. R2<- counter
2. R1 = R1 + 1 counter++; counter--; 2. R2 = R2 - 1
3. counter <- R1 ---- ---- 3. counter <- R2
Shared Variable
---- ----
} }
Process - 1 Process - 2
• Output?
P1 P2 P1 (1) P2(1,2,3) P1(2,3) P2 P1
Context Switch
5
Why Synchronization?
{ {
--- ---
1. R1<- counter --- int counter = 5 --- 1. R2<- counter
2. R1 = R1 + 1 counter++; counter--; 2. R2 = R2 - 1
3. counter <- R1 ---- ---- 3. counter <- R2
Shared Variable
---- ----
} }
Process - 1 Process - 2
• Output?
P1 P2(1) P1 (1,2,3) P2(2,3) P1 P2 P1
Context Switch
6
Why Synchronization?
• What could happen because of SM?
• Final Value of Shared Variable depends
• On the Order of Execution of Instructions
• On which instruction the process is preempted
7
Race Condition
• Situation when several processes access and manipulate the same
data
• Critical Section:-It is the part of the program where shared resources are
accessed.
• The outcome of a race condition: O/P depends on the order in which
the accesses to the data took place.
{
--- CS
---
counter++;
----
----
}
Process - 1
8
How to Prevent Race Condition?
• Synchronization
• Ensure only one process manipulates the shared data at a time
9
Solution to Critical Section Problem
Mutual Exclusion:-
No more than one process in critical section at a time.
Progress:-
When no process is in the critical section, any process that requests entry to the critical section must
be permitted without any delay.
10
Locks and Unlocks
All critical section problem use techniques known as locking and unlocking
in order to solve the critical section problem
11
When to use locking mechanism?
Single instruction by themselves are atomic
Multiple instruction need to be explicitly made atomic
Need explicit locking and unlocking
12
When to use locking mechanism?
• Using Interrupts
• Software solution for critical section problem
• Simple
• When interrupts are disabled, context switches won’t happen
• Requires Privileges
• User processes generally cannot disable interrupts
• Not suited for multicore systems
Process 1 Process 2
While(1){ While(1){
Disable interrupts Disable interrupts
Critical section Critical section
Enable Interrupts Enable Interrupts
} }
13
Software Solution 1
int turn=1;
Process 1 Process 2
while(1){ while(1){
while(turn ==2); while(turn==1);
14
Software Solution 2
turn2=false;
Process 1 turn1=false; Process 2
while(1){ while(1){
while(turn2==true); while(turn1==true);
turn1=true; turn2=true;
Critical section Critical section
turn1 =false; turn2 =false;
} }
15
Software Solution 3
Process 1
turn2=false; Process 2
while(1){ turn1=false;
while(1){
turn1=true;
turn2=true;
while(turn2==true);
while(turn1==true);
Critical section
Critical section
turn2 =false;
turn1 =false;
}
}
16
flag2=false;
flag1=false; Process 2
Process 1 turn
while(1){ while(1){
flag1=true; flag2=true;
turn=2; turn =1
while(flag2==true && turn =2); while(flag1==true && turn=1);
17
Bakery Algorithm
Requesting Access:
●
When a process wants to enter the critical section, it sets its flag to true.
●
chooses a number that is greater than the current maximum label value among all process. This is
done atomically to ensure the correct ordering.
18
boolean flag[N] = {false};
lock(i){
flag[i] = true;
label[i] = max(label[0], ..., label[N-1]) + 1;
flag[i] = false;
for j = 0 to N-1{
if j != i{ unlock(i)
while (flag[j]); // Wait until j takes the value and notinterested {
label[i]=0;
while( label[j] != 0 and (label[j] < label[i] or label[j] == label[i] }
and j < i)):
}}
}
19
20
21
Thank You
Any Questions?
22
Operating Systems (CS3000)
Lecture – 20
(Process Synchronization - 2)
2
Hardware Solution 2-Swap (Version 1)
int locked=0, val=1;
int Swap(int *locked, int val)
{
int prev=*locked;
*locked=val; Process 2
Process 1
return prev;
while(1){
while(1){ while(Swap(&locked, val))==1);
while(Swap(&locked, val))==1); }
Critical section
Critical section locked=0;
locked=0; }
}
3
Hardware Solution 2-Swap (Version-2)
int locked=0;
int Swap(int *locked, int *val)
{
int temp=*locked;
Process 1 *locked=*val; Process 2
*val=temp;
While(1){ While(1){
Val=1; Val=1;
} while(Swap(&locked, val))==1);
while(Swap(&locked, val))==1);
Critical section
Critical section
locked=0;
locked=0;
}
}
4
Hardware Solution -For n process)
Process { boolean waiting[n];
waiting [i] = TRUE; boolean lock=False;
key = TRUE;
while (waiting[i] && key)
key = TestAndSet(&lock);
waiting [i] = FALSE;
// critical section
j = ( i + 1) % n ;
w h i l e ( (j ! = i) && ! w a i t i n g [ j ] )
j = (j + 1) % n ;
if (j == i)
lock = FALSE;
else
waiting[j] = FALSE;
// remainder section
}
5
High Level Techniques
Spinlocks
Mutex
Semaphore
6
Spinlocks
int locked=0;
void acquire(int *locked)
Process 1 { Process 2
while(1)
While(1){ { While(1){
acquire(&locked) if(swap(locked, val)==0) acquire(&locked)
Break;
Critical section } Critical section
release(&locked) } release(&locked)
} }
void release (int *locked)
{
*locked=0;
}
7
Mutex
int locked=0;
void lock(int *locked)
{
Process 1 while(1) Process 2
{
While(1){ if(swap(locked, val)==0) While(1){
lock(&locked) Break; acquire(&locked)
}
Else
Critical section Critical section
sleep();
unlock(&locked) release(&locked)
}
} }
void release (int *locked)
{
*locked=0;
wakeup();
}
8
Thundering Herd Problem
A large number of processes wake up almost
simultaneously, when the even occurs
Leading to more context switching
Could lead to starvation
Wasted cpu cycle
Solutions:
9
Thank You
Any Questions?
10
Operating Systems (CS3000)
Lecture – 20
(Process Synchronization - 3)
2
Producer Consumer Problem
Producer()
Consumer()Process 2
{
{
while(true)
while(true)
While(1){
{ acquire(&locked)
{
Item =produce_item();
Critical section
lock(mutex);
release(&locked)
item=remove_item();
}
lock(mutex);
Count--;
insert_item(Item);
unlock(mutex);
Count++;
unlock(mutex);
consume_item()
}}
}}
3
Semaphore
Proposed by Dijkstras void down(int *S)
{
up/P/signal
while(*S<=0);
down/V/wait *S--;
}
Semaphore: blocking and unblocking
Counting and Binary void up(int *S)
{
*S++;
}
4
Semaphore
typedef struct { signal(semaphore *S) {
int value;
wait(semaphore *S) { S->value++;
struct process *
S->value--; list ; if (S->value <= 0) {
if (S->value < 0) { } semaphore; remove a process P from S->list;
add this process to S->list; wakeup(P);
block()/sleep(); }
} }
}
5
• Deadlock – two or more processes are waiting indefinitely for an event that can be caused by only
one of the waiting processes
• Let S and Q be two semaphores initialized to 1
P0 P1
wait (S); wait (Q);
wait (Q); wait (S);
. .
. .
6
Consider two concurrent process ‘P’ and ‘Q’ executes their response code
Process P code Process Q Code
What should be the binary operation on W, X, Y, Z and what should be the initial
value of binary semaphore ‘S’ and ‘T’ in order to get the output always as 0011
0011 0011……
(a) w=P(T), X=V(T), Y=P(S), Z=V(S), S=T=1.
(b) w=P(T), X=V(T), Y=P(S), Z=V(S), S=1, T=0.
(c) w=P(T), X=V(S), Y=P(S), Z=V(T), S=T=1.
(d) w=P(T), X=V(S), Y=P(S), Z=V(T), S=0,T=1.
7
Thank You
Any Questions?
8
Operating Systems (CS3000)
Lecture – 20
(Process Synchronization - 4)
2
Producer Consumer Problem
N buffers, each can hold one item
Semaphore mutex initialized to the value 1
Semaphore full initialized to the value 0
Semaphore empty initialized to the value N.
Full =4
Empty=2
N=6
3
Producer Consumer Problem
Producer() Consumer()
{ {
while(true) while(true)
{ {
Item =produce_item();
item=remove_item();
Count--;
insert_item(Item);
consume_item()
}}
}}
4
Producer Consumer Problem
Producer()
Consumer()Process 2
{
{
while(true)
while(true)
While(1){
{ acquire(&locked)
{
Item =produce_item();
Critical section
release(&locked)
item=remove_item();
}
insert_item(Item);
consume_item()
}}
}}
5
Producer Consumer Problem
Producer() Consumer()
{ { Process 2
while(true) while(true)
While(1){
{ { acquire(&locked)
Item =produce_item();
wait (full);
Critical section
wait (empty); wait (mutex);
release(&locked)
wait (mutex); }
item=remove_item();
// insert_item(Item);
signal (mutex);
signal (mutex); signal (empty);
signal (full); consume_item(item);
}} }}
6
Reader Writer Problem
A data set is shared among a number of concurrent processes
Readers – only read the data set; they do not perform any updates
Writers – can both read and write
Problem – allow multiple readers to read at the same time. Only one single
writer can access the shared data at the same time
Shared Data
Data set
Semaphore mutex initialized to 1
Semaphore wrt initialized to 1
Integer readcount initialized to 0
7
Reader Writer Problem
do {
do { wait(mutex);
readcount + + ;
wait (wrt) ;
if (readcount == 1)
wait(wrt);
// writing is performed signal(mutex);
// reading is performed
wait (mutex) ,
signal (wrt) ; readcount--;
} while (TRUE); if (readcount == 0)
signal(wrt);
signal(mutex);
} while(TRUE);
8
9
Dining Philosophers Problem
Philosophers either think or
eat
To eat, a philosopher needs
to hold both forks (the one
on his left and the one on
his right)
If the philosopher is not
eating , he is thinking
Problem Statement:
Develop an algorithm where
no philosopher starves
10
Solution 1
#define N 5
Void philosopher(int i){
While(TRUE){
think(); //for some_time
Take_fork(R);
Take_fork(L);
eat();
put_fork(L);
put_fork(R);
}
}
11
12
Thank You
Any Questions?
13
Operating Systems (CS3000)
Lecture – 20
(Process Synchronization - 5)
Problem Statement:
Develop an algorithm where
no philosopher starves
2
Solution 1
#define N 5
Void philosopher(int i){
While(TRUE){
think(); //for some_time
Take_fork(R_i);
Take_fork(L_i);
eat();
put_fork(L_i);
put_fork(R_i);
}
}
3
#define N 5
4
#define N 5
Solution 3 Void philosopher(int i){
While(TRUE){
think(); //for some_time
lock(mutex);
Take_fork(R_i);
Take_fork(L_i);
eat();
put_fork(L_i);
put_fork(R_i);
unlock(mutex);
}
}
5
#define N 5
Solution 4 semaphore chopstick[5];
Void philosopher(int i){
While(TRUE){
wait (chopstick [i] );
wait(chopstick [ (i + 1) % 5] ) ;
// eat
signal(chopstick [i]);
signal(chopstick [(i + 1) % 5]);
}
}
6
Solution 5 Void take_fork(int i){
Void take_fork(int i){
#define N 5 lock(mutex);
semaphore S[5]; state[i]=hungry; lock(mutex);
states[i]={thinking, test(i) state[i]=thinking;
hungry, eating} unlock(mutex); test(left);
Void philosopher(int i) down(S[i]); text(right);
{ unlock(mutex);
}
While(TRUE){ }
Think();
take_fork(i); Void test(int i){
// eat if(state[i]=hungry && state[Left]!=eating && state[right]!=eating)
put_fork(i) {
}
state[i]=eating;
}
up[i];
}
}
7
8
Thank You
Any Questions?
9
Deadlocks
Dr. Jaishree Mayank
Deadlock
• In a multiprogramming environment, several processes may compete
for a finite number of resources.
• A process requests resources; and if the resources are not available at
that time, the process enters a waiting state.
• Sometimes, a waiting process is never again able to change state,
because the resources it has requested are held by other processes.
• This situation is called a deadlock.
System Model
• A system consists of a finite number of resources to be
distributed among a number of competing processes.
• The resources are partitioned into several types, each consisting
of some number of identical instances.
• Example of Resource Types
[Link] Wait:-
A set {P0, P1, P2, --, Pn} of waiting processes must exist such that
P0 is waiting for a resource held by P1, P1 is waiting for a resource
held by P2, … , Pn-1 is waiting for a resource held by Pn.
• Set of Edges:-
• Request Edge:-
• A directed edge from process type Pi to resource type Rj (Pi -> Rj)
• Assignment Edge:-
• A directed edge from resource type Rj to process type Pi (Pi -> Rj)
• Processes • P= {P1, P2, P3}
• R= {R1, R2, R3, R4}
• Resource
…. • Request Edge= {P1->R1, P2->P3}
• Assignment Edge= {R1->P2, R3->P3,
R2->P2}
R1 R3
. . • Resource Instances
• One instance of R1
• One instance of R3
P3
• Two instance of R2
P1 P2 • Tree instance of R4
• Observation:
..
R2
…
• No Cycle:- No deadlock
• Cycle:- Deadlock may exist
R4
Example1 R1 Example 2
. R3
. .. P2
P1 P2 P3 R1
P1
P3
…
.
R2
R4 .. P4
R2
Example of Deadlock
P1 P2 P3 Process1 Process2
CD CD CD
Drive Drive Drive
CD
Printer1 Drive
P1 P2 P3
CD CD CD
Drive Drive Drive
Methods for Handling Deadlock
Three ways to deal with deadlock problems:
Prevention : Ensure that the system will never enter a
deadlock state
Disadvantages
[Link] utilization may be low
2. Starvation is possible
3. No Preemption
• Preemption must hold.
• Protocol 1:-If a process is holding some resources and requests another resource
that cannot be immediately allocated to it(that is, the process must wait), then
all resources currently being held are pre-empted.
• Protocol 2:-
If a process requests some resources, we first check whether they are available.
If they are available, we allocate them.
If not, check are they allocated to some other resource which is also waiting for
additional resource. If so, we pre-empt the desired resources from the waiting
process and allocate to the requesting process.
Applicable for CPU registers and memory space but it cannot be applied to
resources as printers and tape drives.
4. Circular wait
• To impose a total ordering of all the resource types and
to require that each process requests in increasing order
of enumeration.
Deadlocks
Methods for Handling Deadlocks
• Deadlock Prevention
• Deadlock Avoidance
• Deadlock Detection and Recover
Deadlock Prevention
• At least one of these conditions cannot hold, we can prevent the
occurrence of a deadlock
• Mutual Exclusion – not required for sharable resources; must hold for non-sharable resources
• Hold and Wait – must guarantee that whenever a process requests a resource, it does not hold
any other resources
• Require process to request and be allocated all its resources before it begins execution,
• allow process to request resources only when the process has none
• Low resource utilization;
• starvation possible
Deadlock Prevention (Cont.)
• No Preemption –
• If a process that is holding some resources requests another resource that
cannot be immediately allocated to it, then all resources currently being held
are released
• Preempted resources are added to the list of resources for which the process
is waiting
• Process will be restarted only when it can regain its old resources, as well as
the new ones that it is requesting
• Circular Wait – impose a total ordering of all resource types, and require that
each process requests resources in an increasing order of enumeration
Deadlock Avoidance
• Requires that the system has some additional a priori
information available.
• Simplest and most useful model requires that each process declare the
maximum number of resources of each type that it may need
• If Pi resource needs are not immediately available, then Pi can wait until all
Pj have finished
• When Pj is finished, Pi can obtain needed resources, execute, return
allocated resources, and terminate
• When Pi terminates, Pi +1 can obtain its needed resources, and so on
Safe, Unsafe , Deadlock State
Deadlock avoidance algorithm
• Single instance of a resource type
• Use a resource-allocation graph
• When a process gets all its resources it must return them in a finite
amount of time
Data Structures for the Banker’s
Algorithm
• Let n = number of processes, and m = number of resources types.
• Mutual Exclusion – not required for sharable resources; must hold for non-sharable resources
• Hold and Wait – must guarantee that whenever a process requests a resource, it does not hold
any other resources
• Require process to request and be allocated all its resources before it begins execution,
• allow process to request resources only when the process has none
• Low resource utilization;
• starvation possible
Deadlock Prevention (Cont.)
• No Preemption –
• If a process that is holding some resources requests another resource that
cannot be immediately allocated to it, then all resources currently being held
are released
• Preempted resources are added to the list of resources for which the process
is waiting
• Process will be restarted only when it can regain its old resources, as well as
the new ones that it is requesting
• Circular Wait – impose a total ordering of all resource types, and require that
each process requests resources in an increasing order of enumeration
Deadlock Avoidance
• Requires that the system has some additional a priori
information available.
• Simplest and most useful model requires that each process declare the
maximum number of resources of each type that it may need
• If Pi resource needs are not immediately available, then Pi can wait until all
Pj have finished
• When Pj is finished, Pi can obtain needed resources, execute, return
allocated resources, and terminate
• When Pi terminates, Pi +1 can obtain its needed resources, and so on
Safe, Unsafe , Deadlock State
Deadlock avoidance algorithm
• Single instance of a resource type
• Use a resource-allocation graph
• When a process gets all its resources it must return them in a finite
amount of time
Data Structures for the Banker’s
Algorithm
• Let n = number of processes, and m = number of resources types.
Lecture – 20
(Memory Management – 1)
permanently.
• Primary memory – only large Register
storage media that the CPU
can access directly. Cache
Main Memory
• Secondary storage – extension
of main memory that provides Secondary Memory
large nonvolatile storage
capacity
Execution of Program (Process)
• #include<stdio.h> • Process
int main(){ • A program in execution
char str[]=“Hello World\n”; • Present in the RAM
print(str); • Comprises of
} • Executable Instructions
• Stack
• Heap
Compile (gcc hello.c) • State in the OS (in the kernel)
3
Contiguous Memory Allocation
5
Multiprogramming
RAM
6
Memory Management Scheme
• Multiple processes can occupy the RAM simultaneously
• Using Memory Management Scheme
• Contiguous
• Fixed
• Variable or Dynamic
• Non-Contiguous (Modern Scheme)
7
Fixed Scheme
• User memory size=25KB, no. of partition=5
• P0=4KB, P1=3KB, P2=6KB, P3=4KB, P4=5KB, P5=5KB
P5 5KB P3 5KB
P4 5KB P2 8KB
Internal
5KB fragmentation
P3 P1 4KB
5KB 2KB
P1
P0 5KB P0 6KB
OS OS
8
Fixed Scheme
• The memory is divided into • Issues
a fixed number of partitions • Internal Fragmentation
• Limit in process size
• The number of partitions is
• Degree of multiprogramming
fixed. is limited
• Partition size can be equal
or unequal
• Degree of
multiprogramming depends
on the no. of partitions.
9
Variable Scheme
• User memory size=25KB
• P1=10KB, P2=8KB, P3=6KB
• P2 completed, P4 arrives=9KB 1KB free
7KB free P3 6KB P3
15KB free
8KB
P2 P2
10KB P1 P1
P1 P1
OS OS OS OS
10
Variable Scheme
• Initially, the memory will be • Advantages:
full contiguous free block. • No internal
• Whenever a request by a fragmentation
process comes, accordingly • No limitation on the
the partition will be made. number of processes
• Size of the process is
limited by the available
RAM size
• Issues
• External Fragmentation
• Solution:
11
Memory Management Unit
• In MMU scheme, adds the relocation register value to every address generated
by a user process
• The user program deals with logical addresses; it never sees the real physical addresses
12
Memory Management Unit
Assume logical address is 20
Base address=10
Limit address= 40
Relocation address=12000
13
Thank You
Any Questions?
14
Operating Systems (CS3000)
Lecture – 20
(Memory Management – 2)
Page number (p) – used as an index into a page table which contains base address of each
page in physical memory
Page offset (d) – combined with base address to define the physical memory address that is
sent to the memory unit (no. Of bits required to represent the page size or word no of page)
frame number (f) – used to represent frame number which is a base address base address of
each page in physical memory
2. Consider the physical memory space is 64MB and 32-bit virtual address space. Page size is 4KB,
what is the approximate size of page table?
(a) 2 MB (b) 3MB (c ) 4 MB (d) 6 MB
Problems
3. Consider the virtual address space is 32 bit.
Page size=4KB. Page table entries of 4 byte. What is the approximate size of page table size?
(a)2MB (b) 3MB (c) 4 MB (d) 8MB
4. Consider the computer system implements 40 bit virtual address and Page size is 16KB, what is
the approximate size of page table, if each page table entry is 48 bits.
(a)398MB (b) 48 MB(c) 192 MB(d) 96MB
Hardware Implementation of Page-table
Case1: Implement the page table as a set of dedicated registers
Case2:-Keep the page table in main memory and a page table base register (PTBR)
Problem:- 2 memory accesses (one for page table and one for actual byte)
Solution of Case 2
TLB is high-speed cache memory.
It consists of two parts : key and value
Search is fast
Few of the page-table entries
When logical addresses is generated by the CPU, its page number is presented to the TLB.
If page number is found, its frame number is easily available and used to access the memory.
If not found in the TLB, a memory reference to the page table is made.
After accessing, we add the page number and frame number to the TLB.
Paging With TLB
Effective Access Time
• Associative Lookup = e time unit
• Assume memory cycle time is 1 microsecond
• Hit ratio (a) – percentage of times that a page number is found in TLB;
Sol:-
Problem 1 Solution
Consider that 80-percent hit ratio means that we find the desired page number in the
TLB 80 percent of the time.
Assume it takes 20 nanoseconds to search the TLB and 100 nanoseconds to access
memory.
Find the effective memory-access time.
Sol:-EAT= TLB hit (TLB access time+Memeory acc time)+(1-TLB hit) (TLB AT+2MAT)
=0.8(20+100)+0.2(20+200)
=96+44
= 140ns
Problem 2
If effective memory access time is given as 160ns. We assume 90-percent hit ratio
means that we find the desired page number in the TLB 90 percent of the time.
100 nanoseconds to access memory.
Find the TLB access time.
Sol:-
Problem 2
If effective memory access time is given as 160ns. We assume 90-percent hit ratio
means that we find the desired page number in the TLB 90 percent of the time.
100 nanoseconds to access memory.
Find the TLB access time.
Sol:-EAT= TLB hit (TLB access time+Memeory acc time)+(1-TLB hit) (TLB AT+2MAT)
160=0.9(T+100)+0.1(T+200)
160=1T+90+20
T= 50ns(TLB access time)
Memory Protection Using bit
Valid-invalid bit attached to each entry in the page table:
• “valid” indicates that the associated page is in the process logical address space, and is
thus a legal page
• “invalid” indicates that the page is not in the process logical address space
Shared Pages Concept
An advantages of paging is the possibility of sharing common code.
This is particularly important in time-sharing environment.
Shared code
• One copy of read-only (reentrant) code shared among processes (i.e., text
editors, compilers, window systems).
• Shared code must appear in same location in the logical address space of
all processes
• Non-Shared Memory
Total Size=6800KB
• Shared Memory
Total Size=950KB
Thank You
Any Questions?
Operating Systems (CS3000)
Lecture – 20
(Memory Management – 3)
2
Page Table When Some Pages Are Not in Main
Memory
3
Page Fault
If there is a reference to a page, first reference to that page will trap to operating system: page fault
4
Steps in Handling a Page Fault
5
Page Fault
Page Fault Rate 0 <=p <=1.0
if p = 0 no page faults
if p = 1, every reference is a fault
6
Page Fault
Memory access time = 200 nanoseconds = 0.2 microsecond
7
Problem 1
Consider a system which has page fault service time =100ns.
Page fault rate is 65%.
Main memory access time is 1ns.
What is effective memory access time?
Sol: EAT=
8
Problem 2
Let the page fault service time be 10ms in a computer with average memory access
time being 20ns.
If one page fault is generated for every 10^6 memory accesses,
what is the effective access time (approx.) for the memory?
Solution:
EAT=
9
Page Replacement
• Page replacement – find some page in memory, but not really in use, swap it out
• algorithm
• performance – want an algorithm that will result in a minimum number of page faults
• The same page may be brought into memory several times
• Algorithm Structure
1. Find the location of the desired page on the disk
3. Bring the desired page into the (newly) free frame; update the page and frame tables
10
Page Replacement
11
Frame Allocation Schemes
• Each process needs minimum number of pages
si size of process pi
m 64
S si
si 10
m total number of frames s2 127
s 10
ai allocation for pi i m a1
137
64 5
S
127
a2 64 59
137
12
Allocation Schemes
• Priority allocation
• Use a proportional allocation scheme using priorities rather than size
• If process P generates a page fault,
i
• select for replacement one of its frames
• select for replacement a frame from a process with lower priority number
Replacement Schemes
• Global replacement – process selects a replacement frame from the set of all frames; one process
can take a frame from another
• Local replacement – each process selects from only its own set of allocated frames
13
FIFO-Page Replacement
Reference string: 1, 2, 3, 4, 1, 2, 5, 1, 2, 3, 4, 5
Number of fault=
• 4 frames
Number of fault=
14
Normal vs Belady’s Anamoly Graph
15
FIFO-Page Replacement
16
Problem
1. A system uses FIFO policy for page replacement. It has 4 page frames with no
pages loaded to begin with.
The system first accesses 100 distinct pages in some order and then accesses the
same 100 pages but now in the reverse order.
How many page faults will occur?
Solution :
17
Optimal Page Replacement
Reference string: 1, 2, 3, 4, 1, 2, 5, 1, 2, 3, 4, 5
• Replace page that will not be used for longest period of time
• 3 frames
• 4 frames
18
Optimal Page Replacement
19
LRU Page Replacement
Reference string: 1, 2, 3, 4, 1, 2, 5, 1, 2, 3, 4, 5
3 frames
4 frames
20
LRU Page Replacement
21
Thrashing
If a process does not have “enough” pages, the page-fault rate is very high. This leads to:
• low CPU utilization
• OS thinks that it needs to increase the degree of multiprogramming another process added to the
system
22
Thank You
Any Questions?
23
Operating Systems (CS3000)
Lecture – 20
(Memory Management – 4)
Solution:
EAT=
Problems 1
Consider a three level paging scheme with a TLB. Assume no page fault occurs. It
takes 20 ns to search the TLB and 100 ns to access the physical memory. If TLB hit
ratio is 80%, the effective memory access time is _______ ns.
Solution:
EAT= TLB hit(TLB acc. Time +Memory acc. time) +TLB miss(TLB acc. Time+ (L+1)
Memory access time)
= 0.8(120)+0.2(420)
=96+84
=180 ns
Hashed Page Table
Used for handling address spaces larger than 32 bits (or large address
space)
Solution:
Problem 2
Consider a system with logical address of 34 bits and physical address of 39 bits.
Page size is 16KB. The memory is byte addressable. Page-table entry size is 8 bytes.
Calculate the page table size in conventional paging and inverted paging.
Lecture – 20
(Memory Management – 5)
• Segment table – maps two-dimensional physical addresses; each table entry has:
base – contains the starting physical address where the segments reside in memory
limit – specifies the length of the segment
• Segment-table base register (STBR) points to the segment table’s location in memory
Lecture – 20
(Disk Management – 1)
Consider a Disk that has 16 platters. Each platter is divided into two surfaces.
Every surface is divided into 1K tracks. Every track is divided into 512 sectors.
•Then the header will wait for the desired sector as the disk is moving in clockwise or
anticlockwise:
•Seek Time:-The amount of time taken to move the r/w head from its current position to
the desired track.
•Rotational Latency:-The amount of time taken to rotate the track when the read/write
header comes to exact position (sector)
• Transfer time depends on the rotational rate of the disk and the
total size of the track.
• Rotational latency is the additional time waiting for the disk to rotate the desired
sector to the disk head
FCFS Disk Scheduling
SSTF Disk Scheduling
SSTF:-It chooses the pending request closest to the current head position.
• Arm only goes as far as the last request in each direction, then, where the head movement is reversed and
servicing continues
• Arm only goes as far as the last request in each direction, then reverses direction immediately, without first
going all the way to the end of the disk
LOOK Disk Scheduling
C-LOOK Disk Scheduling
Problem
A disk has 200 tracks (numbered 0 through 199).
At a given time, it was servicing the request of reading data from track 120, and at the previous request,
service was for track 90.
The pending requests (in order of their arrival) are for track numbers. 30 70 115 130 110 80 20 25.
How many times will the head change its direction for the disk scheduling policies SSTF(Shortest Seek
Time First), FCFS(First Come Fist Serve), SCAN and C-SCAN
Solution: SSTF
FCFS
SCAN
C-SCAN
Problem
Problem
A disk has 200 tracks (numbered 0 through 199).
At a given time, it was servicing the request of reading data from track 120, and at the previous request,
service was for track 90.
The pending requests (in order of their arrival) are for track numbers. 30 70 115 130 110 80 20 25.
How many times will the head change its direction for the disk scheduling policies SSTF(Shortest Seek
Time First), FCFS(First Come Fist Serve), SCAN and C-SCAN
Solution: SSTF=3
FCFS=4
SCAN=1
C-SCAN=2
Thank You
Any Questions?