Location via proxy:   [ UP ]  
[Report a bug]   [Manage cookies]                

Os Unit Ii

Download as pptx, pdf, or txt
Download as pptx, pdf, or txt
You are on page 1of 69

OPERATING SYSTEMS

Mr.V.Yuvaraj
Assistant Professor – Department of Computer Applications
Dr. N.G.P. ARTS AND SCIENCE COLLEGE
Dr. N.G.P.-KALAPATTI ROAD
COIMBATORE-641 048
Tamil Nadu, India
Mobile: +917502919891,
E-mail: yuvaraj.v@drngpasc.ac.in

Dr. NGPASC
COIMBATORE | INDIA
Chapter 2: Processes

• Process Concept
• Process Scheduling
• Operations on Processes
• Basic Concepts: Scheduling Criteria-
Scheduling Algorithms
• Synchronization: Background - The
Critical - Section Problem -Semaphores.

Dr. NGPASC
COIMBATORE | INDIA
Process Concept

• An operating system executes a variety of programs:


– Batch system – jobs
– Time-shared systems – user programs or tasks
• Textbook uses the terms job and process almost
interchangeably
• Process – a program in execution; process execution must
progress in sequential fashion
• Multiple parts
– The program code, also called text section
– Current activity including program counter, processor registers
– Stack containing temporary data
• Function parameters, return addresses, local variables
– Data section containing global variables
– Heap containing memory dynamically allocated during run time
Dr. NGPASC
COIMBATORE | INDIA
Process Concept (Cont.)

• Program is passive entity stored on disk


(executable file), process is active
– Program becomes process when executable
file loaded into memory
• Execution of program started via GUI
mouse clicks, command line entry of its
name, etc
• One program can be several processes
– Consider multiple users executing the same
program
Dr. NGPASC
COIMBATORE | INDIA
Process in Memory

Dr. NGPASC
COIMBATORE | INDIA
Process State

• As a process executes, it changes state


– new: The process is being created
– running: Instructions are being executed
– waiting: The process is waiting for some event to
occur
– ready: The process is waiting to be assigned to a
processor
– terminated: The process has finished execution

Dr. NGPASC
COIMBATORE | INDIA
Diagram of Process State

Dr. NGPASC
COIMBATORE | INDIA
Process Control Block (PCB)
Information associated with each process
(also called task control block)
• Process state – running, waiting, etc
• Program counter – location of instruction
to next execute
• CPU registers – contents of all process-
centric registers
• CPU scheduling information- priorities,
scheduling queue pointers
• Memory-management information –
memory allocated to the process
• Accounting information – CPU used, clock
time elapsed since start, time limits
• I/O status information – I/O devices
allocated to process, list of open files

Dr. NGPASC
COIMBATORE | INDIA
CPU Switch From Process to Process

Dr. NGPASC
COIMBATORE | INDIA
Threads

• So far, process has a single thread of


execution
• Consider having multiple program counters
per process
– Multiple locations can execute at once
• Multiple threads of control -> threads
• Must then have storage for thread details,
multiple program counters in PCB
• See next chapter

Dr. NGPASC
COIMBATORE | INDIA
Process Representation in Linux

Represented by the C structure task_struct

pid t_pid; /* process identifier */


long state; /* state of the process */
unsigned int time_slice /* scheduling information */
struct task_struct *parent; /* this process’s parent */
struct list_head children; /* this process’s children */
struct files_struct *files; /* list of open files */
struct mm_struct *mm; /* address space of this process */

Dr. NGPASC
COIMBATORE | INDIA
Process Scheduling

• Maximize CPU use, quickly switch processes onto


CPU for time sharing
• Process scheduler selects among available processes
for next execution on CPU
• Maintains scheduling queues of processes
– Job queue – set of all processes in the system
– Ready queue – set of all processes residing in main
memory, ready and waiting to execute
– Device queues – set of processes waiting for an I/O
device
– Processes migrate among the various queues

Dr. NGPASC
COIMBATORE | INDIA
Ready Queue And Various I/O Device Queues

Dr. NGPASC
COIMBATORE | INDIA
Representation of Process Scheduling

 Queueing diagram represents queues, resources,


flows

Dr. NGPASC
COIMBATORE | INDIA
Schedulers
• Short-term scheduler (or CPU scheduler) – selects which process should be
executed next and allocates CPU
– Sometimes the only scheduler in a system
– Short-term scheduler is invoked frequently (milliseconds)  (must be fast)
• Long-term scheduler (or job scheduler) – selects which processes should be
brought into the ready queue
– Long-term scheduler is invoked infrequently (seconds, minutes)  (may be
slow)
– The long-term scheduler controls the degree of multiprogramming
• Processes can be described as either:
– I/O-bound process – spends more time doing I/O than computations, many
short CPU bursts
– CPU-bound process – spends more time doing computations; few very long
CPU bursts
• Long-term scheduler strives for good process mix

Dr. NGPASC
COIMBATORE | INDIA
Addition of Medium Term Scheduling
 Medium-term scheduler can be added if degree of
multiple programming needs to decrease
 Remove process from memory, store on disk,
bring back in from disk to continue execution:
swapping

Dr. NGPASC
COIMBATORE | INDIA
Multitasking in Mobile Systems
• Some mobile systems (e.g., early version of iOS) allow only
one process to run, others suspended
• Due to screen real estate, user interface limits iOS provides
for a
– Single foreground process- controlled via user interface
– Multiple background processes– in memory, running, but not on
the display, and with limits
– Limits include single, short task, receiving notification of events,
specific long-running tasks like audio playback
• Android runs foreground and background, with fewer limits
– Background process uses a service to perform tasks
– Service can keep running even if background process is suspended
– Service has no user interface, small memory use

Dr. NGPASC
COIMBATORE | INDIA
Context Switch
• When CPU switches to another process, the system
must save the state of the old process and load the
saved state for the new process via a context switch
• Context of a process represented in the PCB
• Context-switch time is overhead; the system does
no useful work while switching
– The more complex the OS and the PCB  the longer the
context switch
• Time dependent on hardware support
– Some hardware provides multiple sets of registers per
CPU  multiple contexts loaded at once

Dr. NGPASC
COIMBATORE | INDIA
Operations on Processes

• System must provide mechanisms for:


– process creation,
– process termination,
– and so on as detailed next

Dr. NGPASC
COIMBATORE | INDIA
Process Creation

• Parent process create children processes,


which, in turn create other processes, forming
a tree of processes
• Generally, process identified and managed via
a process identifier (pid)
• Resource sharing options
– Parent and children share all resources
– Children share subset of parent’s resources
– Parent and child share no resources
• Execution options
– Parent and children execute concurrently
– Parent waits until children terminate
Dr. NGPASC
COIMBATORE | INDIA
A Tree of Processes in Linux

Dr. NGPASC
COIMBATORE | INDIA
Process Creation (Cont.)

• Address space
– Child duplicate of parent
– Child has a program loaded into it
• UNIX examples
– fork() system call creates new process
– exec() system call used after a fork()
to replace the process’ memory space with
a new program

Dr. NGPASC
COIMBATORE | INDIA
C Program Forking Separate Process

Dr. NGPASC
COIMBATORE | INDIA
Creating a Separate Process via Windows API

Dr. NGPASC
COIMBATORE | INDIA
Process Termination

• Process executes last statement and then asks the


operating system to delete it using the exit()
system call.
– Returns status data from child to parent (via wait())
– Process’ resources are deallocated by operating system
• Parent may terminate the execution of children
processes using the abort() system call. Some
reasons for doing so:
– Child has exceeded allocated resources
– Task assigned to child is no longer required
– The parent is exiting and the operating systems does not
allow a child to continue if its parent terminates

Dr. NGPASC
COIMBATORE | INDIA
Process Termination
• Some operating systems do not allow child to exists if its parent
has terminated. If a process terminates, then all its children must
also be terminated.
– cascading termination. All children, grandchildren, etc. are
terminated.
– The termination is initiated by the operating system.
• The parent process may wait for termination of a child process by
using the wait()system call. The call returns status
information and the pid of the terminated process
pid = wait(&status);
• If no parent waiting (did not invoke wait()) process is a zombie
• If parent terminated without invoking wait , process is an
orphan

Dr. NGPASC
COIMBATORE | INDIA
Dr. NGPASC
COIMBATORE | INDIA
Basic Concepts

• Maximum CPU
utilization obtained with
multiprogramming
• CPU–I/O Burst Cycle –
Process execution
consists of a cycle of
CPU execution and I/O
wait
• CPU burst followed by
I/O burst
• CPU burst distribution is
of main concern
Dr. NGPASC
COIMBATORE | INDIA
Histogram of CPU-burst Times

Dr. NGPASC
COIMBATORE | INDIA
CPU Scheduler
 Short-term scheduler selects from among the processes
in ready queue, and allocates the CPU to one of them
 Queue may be ordered in various ways
 CPU scheduling decisions may take place when a process:
1. Switches from running to waiting state
2. Switches from running to ready state
3. Switches from waiting to ready
4. Terminates
 Scheduling under 1 and 4 is nonpreemptive
 All other scheduling is preemptive
 Consider access to shared data
 Consider preemption while in kernel mode
 Consider interrupts occurring during crucial OS activities

Dr. NGPASC
COIMBATORE | INDIA
Dispatcher

• Dispatcher module gives control of the


CPU to the process selected by the short-
term scheduler; this involves:
– switching context
– switching to user mode
– jumping to the proper location in the user
program to restart that program
• Dispatch latency – time it takes for the
dispatcher to stop one process and start
another running

Dr. NGPASC
COIMBATORE | INDIA
Scheduling Criteria

• CPU utilization – keep the CPU as busy as


possible
• Throughput – # of processes that complete their
execution per time unit
• Turnaround time – amount of time to execute a
particular process
• Waiting time – amount of time a process has
been waiting in the ready queue
• Response time – amount of time it takes from
when a request was submitted until the first
response is produced, not output (for time-
sharing environment)
Dr. NGPASC
COIMBATORE | INDIA
Scheduling Algorithm Optimization Criteria

• Max CPU utilization


• Max throughput
• Min turnaround time
• Min waiting time
• Min response time

Dr. NGPASC
COIMBATORE | INDIA
First- Come, First-Served (FCFS) Scheduling

Process Burst Time


P1 24
P2 3
P3 3
• Suppose that the processes arrive in the order: P1 , P2 , P3
The Gantt Chart for the schedule is:
P1 P2 P3
0 24 27 30

• Waiting time for P1 = 0; P2 = 24; P3 = 27


• Average waiting time: (0 + 24 + 27)/3 = 17

Dr. NGPASC
COIMBATORE | INDIA
FCFS Scheduling (Cont.)
Suppose that the processes arrive in the order:
P2 , P3 , P1
• The Gantt chart for the schedule is:

P2 P3 P1
0 3 6 30

• Waiting time for P1 = 6; P2 = 0; P3 = 3


• Average waiting time: (6 + 0 + 3)/3 = 3
• Much better than previous case
• Convoy effect - short process behind long process
– Consider one CPU-bound and many I/O-bound processes

Dr. NGPASC
COIMBATORE | INDIA
Shortest-Job-First (SJF) Scheduling

• Associate with each process the length


of its next CPU burst
– Use these lengths to schedule the process
with the shortest time
• SJF is optimal – gives minimum average
waiting time for a given set of processes
– The difficulty is knowing the length of the
next CPU request
– Could ask the user

Dr. NGPASC
COIMBATORE | INDIA
Example of SJF

ProcessArriva l Time Burst Time


P1 0.0 6
P2 2.0 8
P3 4.0 7
P4 5.0 3

• SJF scheduling chart


P4 P1 P3 P2
0 3 9 16 24

• Average waiting time = (3 + 16 + 9 + 0) / 4 = 7


Dr. NGPASC
COIMBATORE | INDIA
Determining Length of Next CPU Burst

• Can only estimate the length – should be similar to the


previous one
– Then pick process with shortest predicted next CPU burst

• Can be done by using the length of previous CPU bursts,


1. t n  actual length of n th CPU burst
using exponential averaging
2.  n 1  predicted value for the next CPU burst
3.  , 0    1
4. Define :  n 1   t n  1    n .

• Commonly, α set to ½
• Preemptive version called shortest-remaining-time-first
Dr. NGPASC
COIMBATORE | INDIA
Prediction of the Length of the Next CPU Burst

Dr. NGPASC
COIMBATORE | INDIA
Examples of Exponential Averaging

•  =0
– n+1 = n
– Recent history does not count
•  =1
– n+1 =  tn
– Only the actual last CPU burst counts
• If we expand the formula, we get:
n+1 =  tn+(1 - ) tn -1 + …
+(1 -  )j  tn -j + …
+(1 -  )n +1 0

• Since both  and (1 - ) are less than or equal to 1, each


successive term has less weight than its predecessor

Dr. NGPASC
COIMBATORE | INDIA
Example of Shortest-remaining-time-first

• Now we add the concepts of varying arrival times and preemption to


the analysis
ProcessA arri Arrival TimeT Burst Time
P1 0 8
P2 1 4
P3 2 9
P4 3 5
• Preemptive SJF Gantt Chart

P1 P2 P4 P1 P3
0 1 5 10 17 26

• Average waiting time = [(10-1)+(1-1)+(17-2)+5-3)]/4 = 26/4 = 6.5 msec

Dr. NGPASC
COIMBATORE | INDIA
Priority Scheduling

• A priority number (integer) is associated with each process


• The CPU is allocated to the process with the highest
priority (smallest integer  highest priority)
– Preemptive
– Nonpreemptive
• SJF is priority scheduling where priority is the inverse of
predicted next CPU burst time
• Problem  Starvation – low priority processes may never
execute
• Solution  Aging – as time progresses increase the priority
of the process

Dr. NGPASC
COIMBATORE | INDIA
Example of Priority Scheduling

ProcessA arri Burst TimeT Priority


P1 10 3
P2 1 1
P3 2 4
P4 1 5
P5 5 2

• Priority scheduling Gantt Chart

• Average waiting time = 8.2 msec


Dr. NGPASC
COIMBATORE | INDIA
Round Robin (RR)

• Each process gets a small unit of CPU time (time quantum


q), 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.
• Timer interrupts every quantum to schedule next process
• Performance
– q large  FIFO
– q small  q must be large with respect to context switch,
otherwise overhead is too high

Dr. NGPASC
COIMBATORE | INDIA
Example of RR with Time Quantum = 4
Process Burst Time
P1 24
P2 3
P3 3
• The Gantt chart is:

P1 P2 P3 P1 P1 P1 P1 P1
0 4 7 10 14 18 22 26 30

• Typically, higher average turnaround than SJF, but better response


• q should be large compared to context switch time
• q usually 10ms to 100ms, context switch < 10 usec

Dr. NGPASC
COIMBATORE | INDIA
Time Quantum and Context Switch Time

Dr. NGPASC
COIMBATORE | INDIA
Turnaround Time Varies With The Time Quantum

80% of CPU bursts


should be shorter than q

Dr. NGPASC
COIMBATORE | INDIA
Multilevel Queue

• Ready queue is partitioned into separate queues, eg:


– foreground (interactive)
– background (batch)
• Process permanently in a given queue
• Each queue has its own scheduling algorithm:
– foreground – RR
– background – FCFS
• Scheduling must be done between the queues:
– Fixed priority scheduling; (i.e., serve all from foreground then
from background). Possibility of starvation.
– Time slice – each queue gets a certain amount of CPU time
which it can schedule amongst its processes; i.e., 80% to
foreground in RR
Dr. NGPASC
– 20%
COIMBATORE
to background in FCFS
| INDIA
Multilevel Queue Scheduling

Dr. NGPASC
COIMBATORE | INDIA
Multilevel Feedback Queue

• A process can move between the various queues;


aging can be implemented this way
• Multilevel-feedback-queue scheduler defined by
the following parameters:
– number of queues
– scheduling algorithms for each queue
– method used to determine when to upgrade a process
– method used to determine when to demote a process
– method used to determine which queue a process will
enter when that process needs service

Dr. NGPASC
COIMBATORE | INDIA
Example of Multilevel Feedback Queue

• Three queues:
– Q0 – RR with time quantum 8 milliseconds
– Q1 – RR time quantum 16 milliseconds
– Q2 – FCFS

• Scheduling
– A new job enters queue Q0 which is served
FCFS
• 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 FCFS and receives
16 additional milliseconds
• If it still does not complete, it is
preempted and moved to queue Q2

Dr. NGPASC
COIMBATORE | INDIA
Multiprocess Architecture – Chrome Browser

• Many web browsers ran as single process (some still do)


– If one web site causes trouble, entire browser can hang or
crash
• Google Chrome Browser is multiprocess with 3 different
types of processes:
– Browser process manages user interface, disk and network
I/O
– Renderer process renders web pages, deals with HTML,
Javascript. A new renderer created for each website opened
• Runs in sandbox restricting disk and network I/O, minimizing effect
of security exploits
– Plug-in process for each type of plug-in

Dr. NGPASC
COIMBATORE | INDIA
Background

• Processes can execute concurrently


– May be interrupted at any time, partially completing execution
• Concurrent access to shared data may result in data
inconsistency
• Maintaining data consistency requires mechanisms to
ensure the orderly execution of cooperating processes
• Illustration of the problem:
Suppose that we wanted to provide a solution to the
consumer-producer problem that fills all the buffers. We can
do so by having an integer counter that keeps track of the
number of full buffers. Initially, counter is set to 0. It is
incremented by the producer after it produces a new buffer
and is decremented by the consumer after it consumes a
buffer.
Dr. NGPASC
COIMBATORE | INDIA
Producer

while (true) {
/* produce an item in next produced */

while (counter == BUFFER_SIZE) ;


/* do nothing */
buffer[in] = next_produced;
in = (in + 1) % BUFFER_SIZE;
counter++;
}

Dr. NGPASC
COIMBATORE | INDIA
Consumer

while (true) {
while (counter == 0)
; /* do nothing */
next_consumed = buffer[out];
out = (out + 1) % BUFFER_SIZE;
counter--;
/* consume the item in next consumed */
}

Dr. NGPASC
COIMBATORE | INDIA
Race Condition

• counter++ could be implemented as

register1 = counter
register1 = register1 + 1
counter = register1

• counter-- could be implemented as


register2 = counter
register2 = register2 - 1
counter = register2
• Consider this execution interleaving with “count = 5” initially:
S0: producer execute register1 = counter {register1 = 5}
S1: producer execute register1 = register1 + 1 {register1 = 6}
S2: consumer execute register2 = counter {register2 = 5}
S3: consumer execute register2 = register2 – 1 {register2 = 4}
S4: producer execute counter = register1 {counter = 6 }
S5: consumer execute counter = register2 {counter = 4}

Dr. NGPASC
COIMBATORE | INDIA
Critical Section Problem

• Consider system of n processes {p0, p1, … pn-1}


• Each process has critical section segment of code
– Process may be changing common variables,
updating table, writing file, etc
– When one process in critical section, no other may
be in its critical section
• Critical section problem is to design protocol to
solve this
• Each process must ask permission to enter critical
section in entry section, may follow critical
section with exit section, then remainder section
Dr. NGPASC
COIMBATORE | INDIA
Critical Section

• General structure of process Pi

Dr. NGPASC
COIMBATORE | INDIA
Algorithm for Process Pi

do {

while (turn == j);


critical section
turn = j;
remainder section
} while (true);

Dr. NGPASC
COIMBATORE | INDIA
Solution to Critical-Section Problem

1. Mutual Exclusion - If process Pi is executing in its critical


section, then no other processes can be executing in their
critical sections
2. Progress - If no process is executing in its critical section
and there exist some processes that wish to enter their
critical section, then the selection of the processes that
will enter the critical section next cannot be postponed
indefinitely
3. Bounded Waiting - A bound must exist on the number of
times that other processes are allowed to enter their
critical sections after a process has made a request to
enter its critical section and before that request is granted
 Assume that each process executes at a nonzero speed
 No assumption concerning relative speed of the n processes
Dr. NGPASC
COIMBATORE | INDIA
Critical-Section Handling in OS

Two approaches depending on if


kernel is preemptive or non-
preemptive
– Preemptive – allows preemption of
process when running in kernel mode
– Non-preemptive – runs until exits kernel
mode, blocks, or voluntarily yields CPU
• Essentially free of race conditions in kernel
mode
Dr. NGPASC
COIMBATORE | INDIA
Dr. NGPASC
COIMBATORE | INDIA
Semaphore

• Synchronization tool that provides more sophisticated ways (than Mutex locks) for process to
synchronize their activities.
• Semaphore S – integer variable
• Can only be accessed via two indivisible (atomic) operations

– wait() and signal()


• Originally called P() and V()

• Definition of the wait() operation


wait(S) {
while (S <= 0)
; // busy wait
S--;
}
• Definition of the signal() operation
signal(S) {
S++;
Dr. NGPASC
}
COIMBATORE | INDIA
Semaphore Usage

• Counting semaphore – integer value can range over an unrestricted domain


• Binary semaphore – integer value can range only between 0 and 1
– Same as a mutex lock
• Can solve various synchronization problems
• Consider P1 and P2 that require S1 to happen before S2
Create a semaphore “synch” initialized to 0
P1:
S1;
signal(synch);
P2:
wait(synch);
S2;
• Can implement a counting semaphore S as a binary semaphore

Dr. NGPASC
COIMBATORE | INDIA
Semaphore Implementation

• Must guarantee that no two processes can execute the


wait() and signal() on the same semaphore at the same
time
• Thus, the implementation becomes the critical section
problem where the wait and signal code are placed in the
critical section
– Could now have busy waiting in critical section
implementation
• But implementation code is short
• Little busy waiting if critical section rarely occupied
• Note that applications may spend lots of time in critical
sections and therefore this is not a good solution

Dr. NGPASC
COIMBATORE | INDIA
Semaphore Implementation with no Busy waiting

• With each semaphore there is an associated waiting queue


• Each entry in a waiting queue has two data items:
– value (of type integer)
– pointer to next record in the list
• Two operations:
– block – place the process invoking the operation on the
appropriate waiting queue
– wakeup – remove one of processes in the waiting queue and
place it in the ready queue
• typedef struct{
int value;
struct process *list;
} semaphore;

Dr. NGPASC
COIMBATORE | INDIA
Implementation with no Busy waiting (Cont.)

wait(semaphore *S) {
S->value--;
if (S->value < 0) {
add this process to S->list;
block();
}
}

signal(semaphore *S) {
S->value++;
if (S->value <= 0) {
remove a process P from S->list;
wakeup(P);
}
}

Dr. NGPASC
COIMBATORE | INDIA
Deadlock and Starvation

• 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);
... ...
signal(S); signal(Q);
signal(Q); signal(S);

• Starvation – indefinite blocking


– A process may never be removed from the semaphore queue in which it is suspended

• Priority Inversion – Scheduling problem when lower-priority


process holds a lock needed by higher-priority process
– Solved via priority-inheritance protocol
Dr. NGPASC
COIMBATORE | INDIA
Dr. NGPASC
COIMBATORE | INDIA 69

You might also like