OS Module-2 (Highlighted)
OS Module-2 (Highlighted)
OS Module-2 (Highlighted)
MODULE 2
MULTITHREADED PROGRAMMING
A thread is a basic unit of CPUutilization.
It consistsof
thread ID
PC
register-set and
stack.
It shares with other threads belonging to the same process its code-section &data-section.
A traditional (or heavy weight) process has a single thread ofcontrol.
If a process has multiple threads of control, it can perform more than one task at a time.
such a process is called multithreaded process
2 ,
Operating Systems
2. In some situations, a single application may be required to perform several similartasks. For ex:
A web-server may create a separate thread for each client requests. This allows the server to
service several concurrent requests.
Resource Sharing By default, threads share the memory (and resources) of the
process to which they belong. Thus, an application is allowed to have several
different threads of activity within the sameaddress-space.
Economy Allocating memory and resources for process-creation is costly. Thus, it is
more economical to create and context-switchthreads.
Utilization of Multiprocessor Architectures In a multiprocessor architecture,
threads may be running in parallel on different processors. Thus, parallelism will
beincreased.
MULTITHREADING MODELS
3 ,
Operating Systems
Many-to-One Model
Many user-level threads are mapped to one kernel thread.
Advantages:
Thread management is done by the thread library in user space, so it isefficient.
Disadvantages:
The entire process will block if a thread makes a blockingsystem-call.
Multiple threads are unable to run in parallel onmultiprocessors.
Forexample:
Solaris green threads
GNU portable threads.
One-to-One Model
Each user thread is mapped to a kernel thread.
Advantages:
It provides more concurrency by allowing another thread to run when a thread
makes a blockingsystem-call.
Multiple threads can run in parallel on multiprocessors.
Disadvantage:
Creating a user thread requires creating the corresponding kernel thread.
For example:
Windows NT/XP/2000, Linux
Many-to-Many Model
Many user-level threads are multiplexed to a smaller number of kernel threads.
Advantages:
Developers can create as many user threads as necessary
The kernel threads can run in parallel on amultiprocessor.
When a thread performs a blocking system-call, kernel can schedule another thread
for execution.
Two Level Model
A variation on the many-to-many model is the two level-model
Similar to M:N, except that it allows a user thread to be bound to kernelthread.
forexample:
HP-UX
Tru64 UNIX
Thread Libraries
It provides the programmer with an API for the creation and management ofthreads.
5 ,
Operating Systems
2. Win32 and
3. Java.
Pthreads
This is a POSIX standard API for thread creation andsynchronization.
This is a specification for thread-behavior, not an implementation.
OS designers may implement the specification in any way theywish.
Commonly used in: UNIX andSolaris.
6 ,
Operating Systems
Win32 threads
Implements the one-to-onemapping
Each threadcontains
A threadid
Registerset
Separate user and kernelstacks
Private data storagearea
The register set, stacks, and private storage area are known as the context of the
threads The primary data structures of a thread include:
ETHREAD (executive threadblock)
KTHREAD (kernel threadblock)
TEB (thread environmentblock)
Java Threads
Threads are the basic model of program-executionin
Java program and
Java language.
The API provides a rich set of features for the creation and management of threads.
All Java programs comprise at least a single thread ofcontrol.
Two techniques for creating threads:
1. Create a new class that is derived from the Thread class and override its run() method.
2. Define a class that implements the Runnable interface. The Runnable interface is
defined as follows:
7 ,
Operating Systems
THREADING ISSUES
8 ,
Operating Systems
THREAD POOLS
The basic idea is to
create a no. of threads at process-startup and
place the threads into a pool (where they sit and wait for work).
Procedure:
1. When a server receives a request, it awakens a thread from the pool.
2. If any thread is available, the request is passed to it for service.
3. Once the service is completed, the thread returns to the pool.
Advantages:
Servicing a request with an existing thread is usually faster than waiting to
create a thread.
The pool limits the no. of threads that exist at any one point.
No. of threads in the pool can be based on actors such as
no. of CPUs
amount of memory and
expected no. of concurrent client-requests.
SCHEDULER ACTIVATIONS
Both M:M and Two-level models require communication to maintain the
appropriate number of kernel threads allocated to theapplication.
Scheduler activations provide upcallsa communication mechanism from the
kernel to the threadlibrary
This communication allows an application to maintain the correct number kernel
threads
One scheme for communication between the user-thread library and the kernel is
known as scheduler activation.
10
Operating Systems
PROCESS SCHEDULING
Basic Concepts
In a single-processor system,
Only one process may run at a time.
Other processes must wait until the CPU is rescheduled.
Objective ofmultiprogramming:
To have some process running at all times, in order to maximize CPU
utilization.
11
Operating Systems
CPU Scheduler
Thisscheduler
selects a waiting-process from the ready-queue and
allocates CPU to the waiting-process.
The ready-queue could be a FIFO, priority queue, tree andlist.
The records in the queues are generally process control blocks (PCBs) of theprocesses.
CPU Scheduling
Four situations under which CPU scheduling decisions takeplace:
1. When a process switches from the running state to the waiting state. For ex; I/O
request.
2. When a process switches from the running state to the ready state. For ex:
when an interrupt occurs.
3. When a process switches from the waiting state to the ready state. For ex:
completion of I/O.
4. When a process terminates.
Scheduling under 1 and 4 is non- preemptive. Scheduling under 2 and 3 is preemptive.
Preemptive Scheduling
This is driven by the idea of prioritizedcomputation.
Processes that are runnable may be temporarilysuspended
Disadvantages:
1. Incurs a cost associated with access toshared-data.
2. Affects the design of the OSkernel.
12
Operating Systems
Dispatcher
It gives control of the CPU to the process selected by the short-termscheduler.
The functioninvolves:
1. Switchingcontext
2. Switching to user mode&
3. Jumping to the proper location in the user program to restart that program
It should be as fast as possible, since it is invoked during every process switch.
Dispatch latency means the time taken by the dispatcherto
stop one process and
start another running.
SCHEDULING CRITERIA:
In choosing which algorithm to use in a particular situation, depends upon the properties
of the various algorithms.Many criteria have been suggested for comparing CPU-
scheduling algorithms. The criteria include the following:
1. CPU utilization: We want to keep the CPU as busy as possible. Conceptually,
CPU utilization can range from 0 to 100 percent. In a real system, it should range
from 40 percent (for a lightly loaded system) to 90 percent (for a heavily used
system).
2. Throughput: If the CPU is busy executing processes, then work is being done.
One measure of work is the number of processes that are completed per time unit,
called throughput. For long processes, this rate may be one process per hour; for
short transactions, it may be ten processes per second.
3. Turnaround time. This is the important criterion which tells how long it takes to
execute that process. The interval from the time of submission of a process to the
time of completion is the turnaround time. Turnaround time is the sum of the
periods spent waiting to get into memory, waiting in the ready queue, executing on
the CPU, and doing I/0.
4. Waiting time: The CPU-scheduling algorithm does not affect the amount of time
during which a process executes or does I/0, it affects only the amount of time that
a process spends waiting in the ready queue.Waiting time is the sum of the periods
spent waiting in the ready queue.
5. Response time:In an interactive system, turnaround time may not be the best
criterion. Often, a process can produce some output fairly early and can continue
computing new results while previous results are being output to the user. Thus,
another measure is the time from the submission of a request until the first response
is produced. This measure, called response time, is the time it takes to start
responding, not the time it takes to output the response. The turnaround time is
generally limited by the speed of the output device.
13
Operating Systems
SCHEDULING ALGORITHMS
CPU scheduling deals with the problem of deciding which of the processes in
the ready-queue is to be allocated theCPU.
Following are some schedulingalgorithms:
1. FCFS scheduling (First Come FirstServed)
2. Round Robin scheduling
3. SJF scheduling (Shortest JobFirst)
4. SRT scheduling
5. Priority scheduling
6. Multilevel Queue schedulingand
7. Multilevel Feedback Queuescheduling
FCFS Scheduling
The process that requests the CPU first is allocated the CPUfirst.
The implementation is easily done using a FIFOqueue.
Procedure:
1. When a process enters the ready-queue, its PCB is linked onto the tail of
thequeue.
2. When the CPU is free, the CPU is allocated to the process at the queue’shead.
3. The running process is then removed from the queue.
Advantage:
1. Code is simple to write & understand.
Disadvantages:
1. Convoy effect: All other processes wait for one big process to get off theCPU.
2. Non-preemptive (a process keeps the CPU until it releasesit).
3. Not good for time-sharingsystems.
4. The average waiting time is generally notminimal.
Example: Suppose that the processes arrive in the order P1, P2,P3.
The Gantt Chart for the schedule is asfollows:
14
Operating Systems
SJF Scheduling
The CPU is assigned to the process that has the smallest next CPUburst.
If two processes have the same length CPU burst, FCFS scheduling is used to break
thetie.
For long-term scheduling in a batch system, we can use the process time limit
specified by the user, as the‘length’
SJF can't be implemented at the level of short-term scheduling, because there is
no way to know the length of the next CPUburst
Advantage:
1. The SJF is optimal, i.e. it gives the minimum average waiting time for a
given set of processes.
Disadvantage:
1. Determining the length of the next CPU burst.
15
Operating Systems
preemptive SJF/SRTF: Consider the following set of processes, with the length
Priority Scheduling
A priority is associated with eachprocess.
The CPU is allocated to the process with the highestpriority.
Equal-priority processes are scheduled in FCFSorder.
Priorities can be defined either internally orexternally.
1. Internally-defined priorities.
Use some measurable quantity to compute the priority of a process.
For example: time limits, memory requirements, no. f open files.
2. Externally-defined priorities.
Set by criteria that are external to the OS For
example:
importance of the process, political factors
Priority scheduling can be either preemptive or non-preemptive.
1.Preemptive
The CPU is preempted if the priority of the newly arrived process is
higher than the priority of the currently running process.
2. Non Preemptive
The new process is put at the head of the ready-queue
Advantage:
Higher priority processes can be executed first.
Disadvantage:
Indefinite blocking, where low-priority processes are left waiting
indefinitely for CPU. Solution: Aging is a technique of increasing
priority of processes that wait in system for a long time.
16
Operating Systems
18
Operating Systems
Useful for situations in which processes are easily classified into different groups.
For example, a common division is made between
foreground (or interactive) processes and
background (or batch) processes.
The ready-queue is partitioned into several separate queues (Figure2.19).
The processes are permanently assigned to one queue based on some property like
memory size
process priority or
process type.
Each queue has its own scheduling algorithm.
For example, separate queues might be used for foreground and background
processes.
20
Operating Systems
21
Operating Systems
Symmetric Multithreading
The basic idea:
1. Create multiple logical processors on the same physical processor.
2. Present a view of several logical processors to the OS.
Each logical processor has its own architecture state, which includes general-
purpose and machine-state registers.
Each logical processor is responsible for its own interrupt handling.
SMT is a feature provided in hardware, notsoftware.
THREAD SCHEDULING
On OSs, it is kernel-level threads but not processes that are being scheduled by theOS.
User-level threads are managed by a thread library, and the kernel is unaware ofthem.
To run on a CPU, user-level threads must be mapped to an associated kernel-
levelthread.
Contention Scope
Twoapproaches:
1. Process-Contention scope
On systems implementing the many-to-one and many-to-many models, the
thread library schedules user-level threads to run on an available LWP.
Competition for the CPU takes place among threads belonging to the
sameprocess.
2. System-Contentionscope
The process of deciding which kernel thread to schedule on theCPU.
Competition for the CPU takes place among all threads in thesystem.
Systems using the one-to-one model schedule threads using onlySCS.
Pthread Scheduling
Pthread API that allows specifying either PCS or SCS during threadcreation.
Pthreads identifies the following contention scopevalues:
1. PTHREAD_SCOPEJPROCESS schedules threads using PCSscheduling.
2. PTHREAD-SCOPE_SYSTEM schedules threads using SCSscheduling.
Pthread IPC provides following two functions for getting and setting the contention
scopepolicy:
1. pthread_attr_setscope(pthread_attr_t *attr, intscope)
2. pthread_attr_getscope(pthread_attr_t *attr, int*scop)
22
Operating Systems
PROCESS SYNCHRONIZATION
A cooperating process is one that can affect or be affected by other processes
executing in the system. Cooperating processes can either directly share a logical
address space (that is, both code and data) or be allowed to share data only through
files or messages.
Concurrent access to shared data may result in data inconsistency. To maintain data
consistency, various mechanisms is required to ensure the orderly execution of
cooperating processes that share a logical address space.
while (true) {
while (true){
while (counter ==0)
; // donothing
nextConsumed =buffer[out];
out = (out + 1) % BUFFER_SIZE;
counter--;
/* consume the item in nextConsumed */
}
23
Operating Systems
Race Condition
When the producer and consumer routines shown above are correct separately, they
may not function correctly when executed concurrently.
Illustration:
Suppose that the value of the variable counter is currently 5 and that the producer and
consumer processes execute the statements "counter++" and "counter--" concurrently.
The value of the variable counter may be 4, 5, or 6 but the only correct result is
counter == 5, which is generated correctly if the producer and consumer execute
separately.
Note: It is arrived at the incorrect state "counter == 4", indicating that four buffers
are full, when, in fact, five buffers are full. If we reversed the order of the statements
at T4 and T5, we would arrive at the incorrect state "counter==6".
Definition Race Condition: A situation where several processes access and
manipulate the same data concurrently and the outcome of the execution depends on
the particular order in which the access takes place, is called a RaceCondition.
To guard against the race condition, ensure that only one process at a time can be
manipulating the variable counter. To make such a guarantee, the processes are
synchronized in some way.
24
Operating Systems
Each process must request permission to enter its critical section. The section of code
implementing this request is the entry section.
The critical section may be followed by an exit section. The remaining code is the
reminder section.
A solution to the critical-section problem must satisfy the following three requirements:
2. Progress:If no process is executing in its critical section and some processes wish to
enter their critical sections, then only those processes that are not executing in their
remainder sections can participate in deciding which will enter its critical section
next, and this selection cannot be postponedindefinitely.
3. Bounded waiting:There exists a bound, or limit, 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 isgranted.
25
Operating Systems
PETERSON'S SOLUTION
Peterson's solution is restricted to two processes that alternate execution between their
critical sections and remainder sections. The processes are numbered Po and P1 or Pi and Pj
where j = 1-i
Peterson's solution requires the two processes to share two data items:
int turn;
boolean flag[2];
turn: The variable turn indicates whose turn it is to enter its critical section. Ex:
if turn == i, then process Pi is allowed to execute in its criticalsection
flag: The flag array is used to indicate if a process is ready to enter its critical
section. Ex: if flag [i] is true, this value indicates that Pi is ready to enter its
critical section.
do {
flag[i] = TRUE;
turn = j;
while (flag[j] && turn == j)
; // do nothing
critical section
flag[i] = FALSE;
remainder section
} while (TRUE);
To enter the critical section, process Pi first sets flag [i] to be true and then sets
turn to the value j, thereby asserting that if the other process wishes to enter the
critical section, it can doso.
If both processes try to enter at the same time, turn will be set to both i and j at
roughly the same time. Only one of these assignments will last, the other will
occur but will be over written immediately.
26
Operating Systems
The eventual value of turn determines which of the two processes is allowed to
enter its critical sectionfirst
27 ,
Operating Systems
SYNCHRONIZATIONHARDWARE
do {
acquire lock
critical section
release lock
remainder section
} while (TRUE);
Definition:
booleanTestAndSet (boolean *target)
{
booleanrv = *target;
*target = TRUE;
return rv:
}
Figure: The definition of the TestAndSet () instruction.
28
Operating Systems
do {
while ( TestAndSet (&lock ))
; // do nothing
// critical section
lock =FALSE;
// remaindersection
} while (TRUE);
Figure: Mutual-exclusion implementation with TestAndSet ()
The Swap() instruction, operates on the contents of two words, it is defined as shown
below
Definition:
void Swap (boolean *a, boolean *b)
{
boolean temp = *a;
*a = *b;
*b = temp:
}
Figure: The definition of the Swap ( ) instruction
Swap() it is executed atomically. If the machine supports the Swap() instruction, then
mutual exclusion can be provided as follows.
A global Boolean variable lock is declared and is initialized to false. In addition, each
process has a local Boolean variable key. The structure of process Pi is shown in
below
do {
key = TRUE;
while ( key == TRUE) Swap
(&lock, &key );
// critical section
lock =FALSE;
// remaindersection
} while (TRUE);
These algorithms satisfy the mutual-exclusion requirement, they do not satisfy the
bounded- waiting requirement.
Below algorithm using the TestAndSet () instruction that satisfies all the critical-
section requirements. The common data structures are
boolean waiting[n];
boolean lock;
do {
waiting[i] = TRUE;
key = TRUE;
while (waiting[i] && key)
key = TestAndSet(&lock);
waiting[i] = FALSE;
// critical section j
= (i + 1) % n;
while ((j != i) && !waiting[j])
j = (j + 1) % n;
if (j == i)
lock = FALSE;
else
waiting[j] = FALSE;
// remainder section
} while (TRUE);
30
Operating Systems
SEMAPHORE
wait (S) {
while S <= 0
; // no-op
S--;
signal (S) {
S++;}
31
Operating Systems
All modifications to the integer value of the semaphore in the wait () and signal()
operations must be executed indivisibly. That is, when one process modifies the
semaphore value, no other process can simultaneously modify that same semaphore
value.
Binary semaphore
The value of a binary semaphore can range only between 0 and1.
Binary semaphores are known as mutex locks, as they are locks that provide
mutual exclusion. Binary semaphores to deal with the critical-section problem for
multiple processes. Then processes share a semaphore, mutex, initialized to1
do {
wait (mutex);
// Critical Section
signal (mutex);
// remainder section
} while (TRUE);
Counting semaphore
The value of a counting semaphore can range over an unrestricteddomain.
Counting semaphores can be used to control access to a given resource
consisting of a finite number ofinstances.
The semaphore is initialized to the number of resources available. Each process
that wishes to use a resource performs a wait() operation on the semaphore.
When a process releases a resource, it performs a signal()operation.
When the count for the semaphore goes to 0, all resources are being used. After
that, processes that wish to use a resource will block until the count becomes
greater than 0.
Implementation
The main disadvantage of the semaphore definition requires busywaiting.
While a process is in its critical section, any other process that tries to enter its
critical section must loop continuously in the entry code.
This continual looping is clearly a problem in a real multiprogramming system,
where a single CPU is shared among many processes.
32
Operating Systems
Busy waiting wastes CPU cycles that some other process might be able to use
productively. This type of semaphore is also called a spinlock because the process
"spins" while waiting for thelock.
typedefstruct {
int value;
struct process *list;
} semaphore;
Each semaphore has an integer value and a list of processes list. When a process must
wait on a semaphore, it is added to the list of processes. A signal() operation removes
one process from the list of waiting processes and awakens that process.
wait(semaphore *S) {
S->value--;
if (S->value < 0) {
add this process to S-
>list; block();
}}
33
Operating Systems
signal(semaphore *S) {
S->value++;
if (S->value <= 0) {
remove a process P
from S->list;
wakeup(P);
}
}
The block() operation suspends the process that invokes it. The wakeup(P)
operation resumes the execution of a blocked process P. These two operations
are provided by the operating system as basic systemcalls.
In this implementation semaphore values may be negative. If a semaphore value
is negative, its magnitude is the number of processes waiting on thatsemaphore.
P0 P1
wait(S); wait(Q);
wait(Q); wait(S);
. .
. .
signal(S); signal(Q);
signal(Q); signal(S);
Suppose that Po executes wait (S) and then P1 executes wait (Q). When Po
executes wait (Q), it must wait until P1 executes signal (Q). Similarly, when P1
executes wait (S), it must wait until Po executes signal(S). Since these signal()
operations cam1ot be executed, Po and P1 are deadlocked.
34
Operating Systems
Bounded-Buffer Problem
N buffers, each can hold one item
Semaphore mutexinitialized to the value 1
Semaphore full initialized to the value0
Semaphore empty initialized to the value N.
35
Operating Systems
Readers-Writers Problem
A data set is shared among a number of concurrentprocesses
Readers – only read the data set; they do not perform anyupdates
Writers – can both read andwrite.
Problem – allow multiple readers to read at the same time. Only one single writer
can access the shared data at the sametime.
SharedData
Dataset
Semaphore mutexinitialized to 1.
Semaphore wrtinitialized to1.
Integer readcountinitialized to 0.
36
Operating Systems
Dining-Philosophers Problem
Consider five philosophers who spend their lives thinking and eating. The philosophers
share a circular table surrounded by five chairs, each belonging to one philosopher. In the
center of the table is a bowl of rice, and the table is laid with five singlechopsticks.
A philosopher gets hungry and tries to pick up the two chopsticks that are closest to her
(the chopsticks that are between her and her left and right neighbors). A philosopher
may pick up only one chopstick at a time. When a hungry philosopher has both her
chopsticks at the same time, she eats without releasing the chopsticks. When she is
finished eating, she puts down both chopsticks and starts thinkingagain.
It is a simple representation of the need to allocate several resources among several
processes in a deadlock-free and starvation-freemanner.
37
Operating Systems
Allowaphilosophertopickupherchopsticksonlyifbothchopsticksareavailable.
Use an asymmetric solution—that is, an odd-numbered philosopher picks up
first her left chopstick and then her right chopstick, whereas an even numbered
philosopher picks up her right chopstick and then her leftchopstick.
Monitor
An abstract data type—or ADT—encapsulates data with a set of functions to
operate on that data that are independent of any specific implementation of the ADT.
A monitor typeis an ADT that includes a set of programmer defined operations that
are provided with mutual exclusion within the monitor. The monitor type also
declares the variables whose values define the state of an instance of that type, along
with the bodies of functions that operate on those variables.
The monitor construct ensures that only one process at a time is active within the
monitor.
38
Operating Systems
39
Operating Systems
Each philosopher I invokes the operations pickup() and putdown() in the following
40
Operating Systems
41
Operating Systems
The Resource Allocator monitor shown in the above Figure, which controls the
allocation of a single resource among competingprocesses.
A process that needs to access the resource in question must observe the following
sequence:
R.acquire(t);
...
access the resource;
...
R.release();
where R is an instance of type ResourceAllocator.
The monitor concept cannot guarantee that the preceding access sequence will be
observed. In particular, the following problems can occur:
A process might access a resource without first gaining access permission to the
resource.
A process might never release a resource once it has been granted access to the
resource.
A process might attempt to release a resource that it neverrequested.
A process might request the same resource twice (without first releasing the
resource).
42
Operating Systems
QUESTION BANK
12. What are semaphores? Explain two primitive semaphore operations. What are its advantages?
13. Explain any one synchronization problem for testing newly proposed sync scheme
14. Explain three requirements that a solution to critical –section problem must satisfy.
43
Operating Systems
15. State Dining Philosopher’s problem and give a solution using semaphores. Write structure of
philosopher.
16. What do you mean by binary semaphore and counting semaphore? With C struct, explain
implementation of wait() and signal. Semaphore as General Synchronization Tool.
17. Describe term monitor. Explain solution to dining philosophers.
18. What are semaphores? Explain solution to producer-cons umer problem using semaphores
19. What is critical section ? Explain the various methods to implement process synchronization.
20. Explain the various classical synchronization problems.
44