OS_module_2 (1)
OS_module_2 (1)
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 */
}
1
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.
2
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.
3
Operating Systems
PETERSON'S SOLUTION
This is a classic software-based solution to the critical-section problem. There are
no guarantees that Peterson's solution will work correctly on modern computer
architectures
Peterson's solution provides a good algorithmic description of solving the critical-
section problem and illustrates some of the complexities involved in designing
software that addresses the requirements of mutual exclusion, progress, and
bounded waiting.
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.
4
Operating Systems
The eventual value of turn determines which of the two processes is allowed to
enter its critical sectionfirst
5
Operating Systems
SYNCHRONIZATIONHARDWARE
The solution to the critical-section problem requires a simple tool-alock.
Race conditions are prevented by requiring that critical regions be protected by
locks. That is, a process must acquire a lock before entering a critical section and
it releases the lock when it exits the critical section
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.
6
Operating Systems 18CS43
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);
SEMAPHORE
wait (S) {
while S <= 0
; // no-op
S--;
signal (S) {
S++;}
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.
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();
}}
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.
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.
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.
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.
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.
Operating Systems
Each philosopher I invokes the operations pickup() and putdown() in the following
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).
Operating Systems