Professional Documents
Culture Documents
Operating System MCA BPUT Unit-4
Operating System MCA BPUT Unit-4
PROCESS SYNCRONIZATION
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 race
condition.
To guard against the race condition above we need to ensure that
only one process at a time can be manipulating the variable counter.
Situation like this occur frequently in OS as different parts of the
system manipulate resources. So, synchronization and coordination
of processes is required.
critical section
exit section
remainder section
} while (TRUE);
do {
flag [i] = TRUE;
turn= j;
while (flag[j] && turn j);
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 do so. 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 overwritten immediately.
The eventual value of turn determines which of the two processes is
allowed to enter its critical section first.
Synchronization Hardware
The critical-section problem could be solved simply in a uniprocessor
environment if we could prevent interrupts from occurring while a
shared variable was being modified.
do {
while (TestAndSet(&lock))
; // do nothing
// critical section
lock = FALSE;
// remainder section
} while (TRUE);
do {
key = TRUE;
while (key == TRUE)
Swap(&lock, &key);
// critical section
lock = FALSE;
// remainder section
} while (TRUE);
Semaphores
• It is a mechanism that can be used to provide synchronization of tasks.
• It is a low-level synchronization mechanism.
• Semaphore will always hold a non-negative integer value.
Types of Semaphores
The two common kinds of semaphores are
• Counting semaphores
• Binary semaphores.
Counting Semaphores
This type of Semaphore uses a count that helps task to be acquired or released
numerous times. If the initial count = 0, the counting semaphore should be
created in the unavailable state.
However, If the count is > 0, the semaphore is created in the available state, and
the number of tokens it has equals to its count.
Binary Semaphores
The binary semaphores are quite similar to counting semaphores, but their
value is restricted to 0 and 1. In this type of semaphore, the wait operation
works only if semaphore = 1, and the signal operation succeeds when
semaphore= 0. It is easy to implement than counting semaphores.
Example of Semaphore
The below-given program is a step by step implementation, which involves
usage and declaration of semaphore.
Advantages of Semaphores
• It allows more than one thread to access the critical section
• Semaphores are machine-independent.
• Semaphores are implemented in the machine-independent code of the
microkernel.
• They do not allow multiple processes to enter the critical section.
• As there is busy waiting in semaphore, there is never a wastage of process
time and resources.
• They are machine-independent, which should be run in the machine-
independent code of the microkernel.
• They allow flexible management of resources.
Disadvantage of semaphores
• One of the biggest limitations of a semaphore is priority inversion.
• The operating system has to keep track of all calls to wait and signal
semaphore.
• Their use is never enforced, but it is by convention only.
• In order to avoid deadlocks in semaphore, the Wait and Signal operations
require to be executed in the correct order.
• Semaphore programming is a complicated, so there are chances of not
achieving mutual exclusion.
• It is also not a practical method for large scale use as their use leads to
loss of modularity.
• Semaphore is more prone to programmer error.
• It may cause deadlock or violation of mutual exclusion due to
programmer error.
[Fig.(B) The structure of the consumer process.] [Figure (A) The structure of the producer process.]
If two readers access the shared data simultaneously, no adverse effects will
result. However, if a writer and some other process (either a reader or a
writer) access the database simultaneously, chaos may ensue.
To ensure that these difficulties do not arise, we require that the writers
have exclusive access to the shared database while writing to the database.
This synchronization problem is referred to as the readers-writers problem.
do { do {
wait(wrt); wait (mutex);
.... readcount++;
// writing is performed
if (readcount == 1)
....
wait (wrt);
signal(wrt);
signal(mutex);
} while (TRUE);
....
// reading is performed
....
wait(mutex);
readcount--;
if (readcount == 0)
signal(wrt);
signal(mutex);
} while (TRUE);
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 single chopsticks. When a philosopher thinks, she does not interact
with her colleagues. From time to time, a philosopher gets hungry and tries to
pick up the two chopsticks that are closest to her (the chopsticks that are
between her left and right neighbours).
A philosopher may pick up only one chopstick at a time. Obviously, she cannot
pick up a chopstick that is already in the hand of a neighbour.
When a hungry philosopher has both her chopsticks at the same time, she
eats without releasing her chopsticks. When she is finished eating, she puts
down both of her chopsticks and starts thinking again.
Monitors
Semaphores provide a convenient and effective mechanism for process
synchronization, using them incorrectly can result in timing errors that are
difficult to detect, since these errors happen only if some particular execution
sequences take place and these sequences do not always occur.
A abstract data type- or ADT- encapsulates private data with public methods
to operate on that data. A monitor type is an ADT which presents a set of
programmer-defined operations that are provided mutual exclusion within
the monitor.
The monitor type also contains the declaration of variables whose values
define the state of an instance of that type, along with the bodies of
procedures or functions that operate on those variables.
Similarly, the local variables of a monitor can be accessed by only the local
procedures.
Philosopher i can set the variable state [i] = EATING only if her two
neighbors are not eating: (state [ (i +4) % 5] ! = EATING) and (state [ (i +1)
% 5] != EATING).
in which philosopher i can delay herself when she is hungry but is unable to
obtain the chopsticks she needs.
This act may result in the suspension of the philosopher process. After the
successful completion of the operation, the philosopher may eat. Following
this, the philosopher invokes the putdown() operation.
monitor dp
{
void pickup(int i) {
state[i] =HUNGRY;
test(i);
if (state [i] ! = EATING)
self [i] . wait() ;
}
void putdown(int i) {
state[i] =THINKING;
test((i + 4) % 5);
test((i + 1) % 5);
}
void test(int i) {
if ((state[(i + 4) % 5] !=EATING) &&
(state[i] ==HUNGRY) &&
(state[(i + 1) % 5] !=EATING)) {
state[i] =EATING;
self[i] .signal();
}
}
initialization_code() {
for (int i = 0; i < 5; i++)
state[i] =THINKING;
}
}
//place in buffer
signal(mutex);
signal(full);
}while(true)
// consumes item
}while(true)
As the consumer is removing an item from buffer, therefore the value of “full”
is reduced by 1 and the value is mutex is also reduced so that the producer
cannot access the buffer at this moment. Now, the consumer has consumed
the item, thus increasing the value of “empty” by 1. The value of mutex is also
increased so that producer can access the buffer now.
wait(mutex);
...
body of F
...
if (next_count > 0)
signal(next);
else
signal(mutex);
x_count++;
if (next_count > 0)
signal(next);
else
signal(mutex);
wait (x_sem) ;
x_count--;
if (x_count > 0) {
next_count++;
signal(x_sem);
wait(next);
next_count--;
}
Atomic Transactions
The mutual exclusion of critical sections ensures that the critical sections are
executed atomically -that is, as one uninterruptible unit. If two critical sections
are instead executed concurrently, the result is equivalent to their sequential
execution in some unknown order.
The mutual exclusion of critical sections ensures that the critical sections are
executed atomically -that is, as one uninterruptible unit. If two critical sections
are instead executed concurrently, the result is equivalent to their sequential
execution in some unknown order.
Volatile storage: Information residing in volatile storage does not usually
survive system crashes. Examples of such storage are main and cache
memory.
Nonvolatile storage: Information residing in nonvolatile storage usually
survives system crashes. Examples of media for such storage are disks and
magnetic tapes.
Stable storage: Information residing in stable storage is never lost (never
should be taken with a grain of salt, since theoretically such absolutes
cannot be guaranteed).
Deadlocks
In a multiprogramming environment, several processes may compete for a
finite number of resources. A process requests resources; 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 waiting processes. This situation is called
a deadlock.
System Models
A system model or structure consists of a fixed number of resources to
be circulated among some opposing processes. The resources are then
partitioned into numerous types, each consisting of some specific
quantity of identical instances. Memory space, CPU cycles, directories
and files, I/O devices like keyboards, printers and CD-DVD drives are
prime examples of resource types. When a system has 2 CPUs, then
the resource type CPU got two instances.
Under the standard mode of operation, any process may use a resource
in only the below-mentioned sequence:
Deadlock Characterization
A deadlock situation can arise if the following four condition hold
simultaneously in a system:
1) Mutual exclusion. At least one resource must be held in a nonsharable
mode; that is, only one process at a time can use the resources.
2) Hold and wait. A process must be holding at least one resource and
waiting to acquire additional resources that are currently being held by
other processes.
3) No preemption. Resources cannot be preempted; that is, a resource can
be released only voluntarily by the process holding it, after that process
has completed its task.
4) Circular wait. A set {P0, P1, ... , 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, and Pn is waiting
for a resource held by Po.
Processes P1, P2, and P3 are deadlocked. Process P2 is waiting for the resource
R3, which is held by process P3. Process P3 is waiting for either process P1 or
process P2 to release resource R2. In addition, process P1 is waiting for process
P2 to release resource R1.
The third solution is the one used by most operating systems, including UNIX
and Windows.
Deadlock Prevention
By ensuring that at least one of these conditions cannot hold, we can prevent
the occurrence of a deadlock.
Mutual Exclusion
The mutual-exclusion condition must hold for nonsharable resources. For
example, a printer cannot be simultaneously shared by several processes.
Sharable resources, in contrast, do not require mutually exclusive access and
thus, cannot be involved in a deadlock.
Deadlock Avoidance
By restraining one of the necessary conditions for deadlock cannot occur and,
hence, that deadlocks cannot hold.
An alternative method for avoiding deadlocks is to require additional
information about how resources are to be requested.
Safe State
A state is safe if the system can allocate resources to each process (up to its
maximum) in some order and still avoid a deadlock. More formally, a system
is in a safe state only if there exists a safe sequence.
A sequence of processes <P1, P2, ..., Pn> is a safe sequence for the current
allocation state if, for each Pi, the resource requests that Pi can still make can
be satisfied by the currently available resources plus the resources held by all
Pj, with j < i.
Resource-Allocation-Graph Algorithm
If no cycle exists, then the allocation of the resource will leave the system
in a safe state. If a cycle is found, then the allocation will put the system in
an unsafe state.
Banker's Algorithm
The name Banker's Algorithm was chosen because the algorithm could be used in
a banking system to ensure that the bank never allocated its available cash in
such a way that it could no longer satisfy the needs of all its customers.
When a new process enters the system, it must declare the maximum
number of instances of each resource type that it may need. This number may
not exceed the total number of resources in the system.
When a user requests a set of resources, the system must determine whether
the allocation of these resources will leave the system in a safe state. If it will,
the resources are allocated; otherwise, the process must wait until some other
process releases enough resources.
For example, there are X number of account holders of a specific bank, and
the total amount of money of their accounts is G.
When the bank processes a car loan, the software system subtracts the
amount of loan granted for purchasing a car from the total money ( G+ Fixed
deposit + Monthly Income Scheme + Gold, etc.) that the bank has.
It also checks that the difference is more than or not G. It only processes the
car loan when the bank has sufficient money even if all account holders
withdraw the money G simultaneously.
Deadlock Detection
If a system does not employ either a deadlock prevention or deadlock avoidance
algorithm then a deadlock situation may occur.
In this case-
• Apply an algorithm to examine state of system to determine whether deadlock
has occurred or not.
• Apply an algorithm to recover from the deadlock.
In the above diagram, resource 1 and resource 2 have single instances. There
is a cycle R1 → P1 → R2 → P2. So, Deadlock is Confirmed.
2) If there are multiple instances of resources:
Detection of the cycle is necessary but not sufficient condition for
deadlock detection, in this case, the system may or may not be in
deadlock varies according to different situations.
1. Process Termination:
To eliminate the deadlock, we can simply kill one or more processes. For this, we
use two methods:
2. Resource Preemption:
To eliminate deadlocks using resource preemption, we preepmt some resources
from processes and give those resources to other processes. This method will raise
three issues –
• (a). Selecting a victim:
We must determine which resources and which processes are to be preempted
and also the order to minimize the cost.
• (b). Rollback:
We must determine what should be done with the process from which
resources are preempted. One simple idea is total rollback. That means abort
the process and restart it.
• (c). Starvation:
In a system, it may happen that same process is always picked as a victim. As
a result, that process will never complete its designated task. This situation is
called Starvation and must be avoided. One solution is that a process must be
picked as a victim only a finite number of times.