SlideShare a Scribd company logo
1 of 8
Download to read offline
Unit IV
Process Synchronization
4.1 Background
The processes may execute either independently or in cooperating way. In the later case, processes
share data with other processes and hence gets afftected by their execution too.
The reason for providing process cooperation:
• Information sharing: Since several users may be interested in the same piece of
information (for instance, a shared file), we must provide an environment to allow
concurrent access to such information.
• Computation speed: If we want a particular task to run faster, we must break it into
subtasks, each of which will be executing in parallel with the others. Notice that such a
speedup can be achieved only if the computer has multiple processing elements (such as
CPUs or I/O channels).
• Modularity: We may want to construct the system in a modular fashion, dividing the
system functions into separate processes or threads.
• Convenience: Even an individual user may work on many tasks at the same time. For
instance, a user may be editing, printing, and compiling in parallel.
Cooperating processes require an interprocess communication (IPC) mechanism for exchanging
data and information. Following is the two fundamental models of IPC:-
1. Shared memory: A region of memory that is shared by cooperating process is created.
Processes can exchange information by reading and writing data to the shared region.
2. Message Passing: It require system calls for every message exchange. In simple terms
standard message is passed among the processes for communication to take place.
Two primitives message can be thought of under this scheme:
• send (destination, &message)
• receive (source, &message)
Comparision of shared memory and messgae passing schemes:
• Shared memory is faster once it is set up because no system calls are required and read/write
operation occurs at normal speed.
• As message passing requires system calls for every message transfer, it is slower.
• In comparision to shared memory, message passing is easier to implement because no new
place is created for message sharing.
Example Problem: Producer-Consumer Problem
The code for the producer process can be defined as follows:
An integer variable counter, initialized to 0. counter is incremented every time we add a new item to
the buffer and is decremented every time we remove one item from the buffer.
The code for the consumer process can be defined as follows:
Although both the producer and consumer routines shown above are correct separately, they may
not function correctly when executed concurrently. For example, 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. Following the execution of these two statements, the
value of the variable counter may be 4, 5, or 6! The only correct result, though, is counter == 5,
which is generated correctly if the producer and consumer execute separately.
We can show that the value of counter may be incorrect as follows. Note that the statement"
counter++" may be implemented in machine language (on a typical machine) as:
register1 = counter
register1 = register1 + 1
counter = register1
Similarly, the statement "counter--" is implemented as follows:
register2 = counter
register2 = register2 - 1
counter= register2
where register1 and register2 are local CPU registers.
The concurrent execution of "counter++" and "counter--" is equivalent to a sequential execution in
which the lower-level statements presented previously are interleaved in some arbitrary order. One
such interleaving is:
Notice that we have 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".
Race Condition
We would arrive at this incorrect state because we allowed both processes to manipulate the
variable counter concurrently. A situation like this, 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 Race Condition.
To guard against the race condition above, we need to ensure that only one process at a time can
manipulate the variable counter. So, we require that the processes be synchronized in some way.
4.2 critical section problem
Consider a system consisting of n processes {Po, P1 , ... , Pn-1}. Each process has a segment of code,
in which they are changing common variables. This piece of code is called critical section.
The important feature of the system is that, when one process is executing in its critical section, no
other process is to be allowed to execute in its critical section. That is, no two processes are
executing in their critical sections at the same time. The critical-section problem gives a protocol
that the processes can use to cooperate.
The general structure of a typical process Pi is shown in following figure. The entry section and
exit section are enclosed in boxes to highlight these important segments of code.
Each process must request permission to enter its critical section. The section of code implementing
this request is the entry section. critical section may be followed by an exit section. The remaining
code is the remainder section.
A solution to the critical-section problem must satisfy the following three requirements:
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 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 carmot be postponed indefinitely.
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 is granted.
Peterson's solution
A classic software-based solution to the critical-section problem is Peterson's solution. In modern
computer architectures, there are no guarantees that Peterson's solution will work correctly.
However the solution is presented because it 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 P0 and P1. For convenience, if the
current process is referred as Pi, we use Pj to denote the other process; that is,
j = 1 - i.
Peterson's solution requires the two processes to share two data items:
• int turn; The variable turn indicates whose turn it is to enter its critical section. That is, if
turn == i, then process Pi is allowed to execute in its critical section.
• boolean flag[2]; The flag array is used to indicate if a process is ready to enter its critical
section. For example, if flag [i] is true, this value indicates that Pi is ready to enter its critical
section.
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 (i.e. j) 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.
But 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.
Proof of the correctness of this solution
We need to show that:
• Mutual exclusion is preserved.
• The progress requirement is satisfied.
• The bounded-waiting requirement is met.
To prove property 1, we note that each Pi enters its critical section only if either flag [j] == false or
turn == i [(while flag[j] && turn == j)].
Also note that, if both processes can be executing in their critical sections at the same time, then
flag [0] ==flag [1] ==true. These two observations imply that P0 and P1 could not have successfully
executed their while statements at about the same time, since the value of turn can be either 0 or 1
but can not be both. Hence, one of the processes -say, Pj -must have successfully executed the while
statencent, whereas Pi had to execute at least one additional statement ("turn== j"). However, at that
time, flag [j] == true and turn == j, and this condition will persist as long as Pi is in its critical
section; as a result, mutual exclusion is preserved.
To prove property 2, we note that a process Pi can be prevented from entering the critical section
only if it is stuck in the while loop with the condition flag [j] ==true and turn== j. If Pj is not ready
to enter the critical section, then flag [j] ==false, and Pi can enter its critical section. If Pj has set
flag [j] to true and is also executing in its while statement, then either turn == i or turn == j.
If turn == i, then Pi will enter the critical section. If turn== j, then Pj will enter the critical section.
However, once Pi exits its critical section, it will reset flag [j] to false, allowing Pi to enter its
critical section.
To prove property 3, If Pj resets flag [j] to true, it must also set turn to i. Thus, since Pi does not
change the value of the variable turn while executing the while statement, Pi will enter the critical
section (progress) after at most one entry by Pj (bounded waiting).
4.3 Synchronization Hardware
Software-based solutions such as Peterson's are not guaranteed to work on modern computer
architectures. Instead, a process must acquire a lock before entering a critical section and it releases
the lock when it exits the critical section as illustrated in following Figure.
In Figure 6.8, we present another algorithm using the TestAndSet () instruction that satisfies all the
critical-section requirements. TestAndSet () is hardware supported atomic instruction i.e. it can't be
interrupted once it has started running.
The common data structures are
boolean waiting[n];
boolean lock;
These data structures are initialized to false.
To prove that the mutual-exclusion requirement is met, we note that process Pi can enter its
critical section only if either waiting [i] == false or key == false. The value of key can become false
only if the TestAndSet () is executed. The first process to execute the TestAndSet () will find key==
false; all others must wait. The variable waiting [i] can become false only if another process leaves
its critical section; only one waiting [i] is set to false, maintaining the mutual-exclusion
requirement.
To prove that the progress requirement is met, we note that the arguments presented for mutual
exclusion also apply here, since a process exiting the critical section either sets lock to false or sets
waiting[j] to false. Both allow a process that is waiting to enter its critical section to proceed.
To prove that the bounded-waiting requirement is met, we note that, when a process leaves its
critical section, it scans the array waiting in the cyclic ordering (i + 1, i + 2, ... , n - 1, 0, ... , i - 1). It
designates the first process in this ordering that is in the entry section (waiting[j] ==true) as the next
one to enter the critical section. Any process waiting to enter its critical section will thus do so
within n - 1 turns.
4.4 Semaphores
The hardware-based solution to the critical-section problem (TestAndSet) are complicated for
application programmers to use. So, we use a synchronization tool called semaphore. A semaphore
S is an integer variable that, apart from initialization, is accessed only through two standard atomic
operations: wait () and signal ().
The wait () operation was originally termed P (from the Dutch proberen, "to test"); signal() was
originally called V (from verhogen, "to increment"). The definition of wait () is as follows:
The definition of signal() is as follows:
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. In addition, in the case of wait (S), the
testing of the integer value of S (S <= 0), as well as its possible modification (S--), must be
executed without interruption.
Usage
There are two types of semaphores: Binary semaphore and Counting semaphore.
Binary Semaphore can have value 0 and 1 only, so sometimes they are also called as mutex locks,
as they are locks that provide mutual exclusion.
We can use binary semaphores to deal with the critical-section problem for multiple processes. The
n processes share a semaphore, mutex, initialized to 1. Each process Pi is organized as shown in
Figure 6.9.
Counting semaphores can be used to control access to a given resource consisting of a finite
number of instances. 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 (thereby
decrementing the count). When a process releases a resource, it performs a signal() operation
(incrementing the count). 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.
We can also use semaphores to solve various synchronization problems. For example, consider two
concurrently running processes: P1 with a statement S1 and P2 with a statement S2 . Suppose we
require that S2 be executed only after S1 has completed. We can implement this scheme readily by
letting P1 and P2 share a common semaphore synch, initialized to 0, and by inserting the statements
S1 ;
signal(synch) ;
in process P1 and the statements
wait(synch);
S2 ;
in process P2.
Because synch is initialized to 0, P2 will execute S2 only after P1 has invoked signal (synch), which
is after statement S1 has been executed.

More Related Content

What's hot

Round robin scheduling
Round robin schedulingRound robin scheduling
Round robin schedulingRaghav S
 
Operating System Process Synchronization
Operating System Process SynchronizationOperating System Process Synchronization
Operating System Process SynchronizationHaziq Naeem
 
Operating Systems Process Scheduling Algorithms
Operating Systems   Process Scheduling AlgorithmsOperating Systems   Process Scheduling Algorithms
Operating Systems Process Scheduling Algorithmssathish sak
 
CPU Scheduling algorithms
CPU Scheduling algorithmsCPU Scheduling algorithms
CPU Scheduling algorithmsShanu Kumar
 
Process Scheduling
Process SchedulingProcess Scheduling
Process Schedulingvampugani
 
cpu scheduling
cpu schedulingcpu scheduling
cpu schedulinghashim102
 
CPU SCHEDULING AND DEADLOCK
CPU SCHEDULING AND	DEADLOCKCPU SCHEDULING AND	DEADLOCK
CPU SCHEDULING AND DEADLOCKVicky Kumar
 
Scheduling algorithm (chammu)
Scheduling algorithm (chammu)Scheduling algorithm (chammu)
Scheduling algorithm (chammu)Nagarajan
 
Processor management
Processor managementProcessor management
Processor managementdev3993
 
CPU scheduling
CPU schedulingCPU scheduling
CPU schedulingAmir Khan
 

What's hot (19)

cpu scheduling in os
cpu scheduling in oscpu scheduling in os
cpu scheduling in os
 
Round robin scheduling
Round robin schedulingRound robin scheduling
Round robin scheduling
 
Process threads operating system.
Process threads operating system.Process threads operating system.
Process threads operating system.
 
Operating System Process Synchronization
Operating System Process SynchronizationOperating System Process Synchronization
Operating System Process Synchronization
 
Real Time System
Real Time SystemReal Time System
Real Time System
 
Operating Systems Process Scheduling Algorithms
Operating Systems   Process Scheduling AlgorithmsOperating Systems   Process Scheduling Algorithms
Operating Systems Process Scheduling Algorithms
 
Process scheduling
Process schedulingProcess scheduling
Process scheduling
 
CPU Scheduling algorithms
CPU Scheduling algorithmsCPU Scheduling algorithms
CPU Scheduling algorithms
 
Process Scheduling
Process SchedulingProcess Scheduling
Process Scheduling
 
Mutual exclusion and sync
Mutual exclusion and syncMutual exclusion and sync
Mutual exclusion and sync
 
cpu scheduling
cpu schedulingcpu scheduling
cpu scheduling
 
CPU SCHEDULING AND DEADLOCK
CPU SCHEDULING AND	DEADLOCKCPU SCHEDULING AND	DEADLOCK
CPU SCHEDULING AND DEADLOCK
 
Scheduling
SchedulingScheduling
Scheduling
 
Scheduling algorithm (chammu)
Scheduling algorithm (chammu)Scheduling algorithm (chammu)
Scheduling algorithm (chammu)
 
Process scheduling
Process schedulingProcess scheduling
Process scheduling
 
Processor management
Processor managementProcessor management
Processor management
 
Real time-embedded-system-lec-02
Real time-embedded-system-lec-02Real time-embedded-system-lec-02
Real time-embedded-system-lec-02
 
CPU scheduling
CPU schedulingCPU scheduling
CPU scheduling
 
OSCh6
OSCh6OSCh6
OSCh6
 

Viewers also liked

Industrial-Analytics-Report-2016-2017-vp-singlepage
Industrial-Analytics-Report-2016-2017-vp-singlepageIndustrial-Analytics-Report-2016-2017-vp-singlepage
Industrial-Analytics-Report-2016-2017-vp-singlepagezahra zahedi
 
Proposal Project Charter
Proposal Project CharterProposal Project Charter
Proposal Project CharterMohammad Ilham
 
Resources and development presentation
Resources and development presentation Resources and development presentation
Resources and development presentation Anannya Anil
 
On elements of deterministic chaos and cross links in non- linear dynamical s...
On elements of deterministic chaos and cross links in non- linear dynamical s...On elements of deterministic chaos and cross links in non- linear dynamical s...
On elements of deterministic chaos and cross links in non- linear dynamical s...iosrjce
 
O traxe rexional galego present. pp 97-2003
O traxe rexional galego present. pp 97-2003O traxe rexional galego present. pp 97-2003
O traxe rexional galego present. pp 97-2003ceip Seara
 
LITERATURE REVIEW: ROLES OF FLAVONOIDS IN HUMAN HEALTH
LITERATURE REVIEW: ROLES OF FLAVONOIDS IN HUMAN HEALTHLITERATURE REVIEW: ROLES OF FLAVONOIDS IN HUMAN HEALTH
LITERATURE REVIEW: ROLES OF FLAVONOIDS IN HUMAN HEALTHKayode Kolawole
 
Flexible pavement failure
Flexible pavement failureFlexible pavement failure
Flexible pavement failureNabaraj Poudel
 
Synthese: la réglementation en matiere de prévention risques santé sécurité
Synthese: la réglementation en matiere de prévention risques santé sécuritéSynthese: la réglementation en matiere de prévention risques santé sécurité
Synthese: la réglementation en matiere de prévention risques santé sécuritéJohnny Keire
 
Offener Brief an den Minister für Sicherheit und Justiz und die Ministerin fü...
Offener Brief an den Minister für Sicherheit und Justiz und die Ministerin fü...Offener Brief an den Minister für Sicherheit und Justiz und die Ministerin fü...
Offener Brief an den Minister für Sicherheit und Justiz und die Ministerin fü...drs Sandra Irene Veenstra, AMI grad
 
Direct Method (DM) of Language Teaching
Direct Method (DM) of Language TeachingDirect Method (DM) of Language Teaching
Direct Method (DM) of Language TeachingAyesha Bashir
 

Viewers also liked (12)

Holistic Awareness
Holistic AwarenessHolistic Awareness
Holistic Awareness
 
Industrial-Analytics-Report-2016-2017-vp-singlepage
Industrial-Analytics-Report-2016-2017-vp-singlepageIndustrial-Analytics-Report-2016-2017-vp-singlepage
Industrial-Analytics-Report-2016-2017-vp-singlepage
 
resume
resumeresume
resume
 
Proposal Project Charter
Proposal Project CharterProposal Project Charter
Proposal Project Charter
 
Resources and development presentation
Resources and development presentation Resources and development presentation
Resources and development presentation
 
On elements of deterministic chaos and cross links in non- linear dynamical s...
On elements of deterministic chaos and cross links in non- linear dynamical s...On elements of deterministic chaos and cross links in non- linear dynamical s...
On elements of deterministic chaos and cross links in non- linear dynamical s...
 
O traxe rexional galego present. pp 97-2003
O traxe rexional galego present. pp 97-2003O traxe rexional galego present. pp 97-2003
O traxe rexional galego present. pp 97-2003
 
LITERATURE REVIEW: ROLES OF FLAVONOIDS IN HUMAN HEALTH
LITERATURE REVIEW: ROLES OF FLAVONOIDS IN HUMAN HEALTHLITERATURE REVIEW: ROLES OF FLAVONOIDS IN HUMAN HEALTH
LITERATURE REVIEW: ROLES OF FLAVONOIDS IN HUMAN HEALTH
 
Flexible pavement failure
Flexible pavement failureFlexible pavement failure
Flexible pavement failure
 
Synthese: la réglementation en matiere de prévention risques santé sécurité
Synthese: la réglementation en matiere de prévention risques santé sécuritéSynthese: la réglementation en matiere de prévention risques santé sécurité
Synthese: la réglementation en matiere de prévention risques santé sécurité
 
Offener Brief an den Minister für Sicherheit und Justiz und die Ministerin fü...
Offener Brief an den Minister für Sicherheit und Justiz und die Ministerin fü...Offener Brief an den Minister für Sicherheit und Justiz und die Ministerin fü...
Offener Brief an den Minister für Sicherheit und Justiz und die Ministerin fü...
 
Direct Method (DM) of Language Teaching
Direct Method (DM) of Language TeachingDirect Method (DM) of Language Teaching
Direct Method (DM) of Language Teaching
 

Similar to Process Synchronization

Operating system 23 process synchronization
Operating system 23 process synchronizationOperating system 23 process synchronization
Operating system 23 process synchronizationVaibhav Khanna
 
Process synchronization
Process synchronizationProcess synchronization
Process synchronizationAbeera Naeem
 
Lecture 5- Process Synchronization (1).pptx
Lecture 5- Process Synchronization (1).pptxLecture 5- Process Synchronization (1).pptx
Lecture 5- Process Synchronization (1).pptxAmanuelmergia
 
Mutual Exclusion using Peterson's Algorithm
Mutual Exclusion using Peterson's AlgorithmMutual Exclusion using Peterson's Algorithm
Mutual Exclusion using Peterson's AlgorithmSouvik Roy
 
Process Synchronization -1.ppt
Process Synchronization -1.pptProcess Synchronization -1.ppt
Process Synchronization -1.pptjayverma27
 
Process synchronizationfinal
Process synchronizationfinalProcess synchronizationfinal
Process synchronizationfinalmarangburu42
 
Operating Systems - "Chapter 5 Process Synchronization"
Operating Systems - "Chapter 5 Process Synchronization"Operating Systems - "Chapter 5 Process Synchronization"
Operating Systems - "Chapter 5 Process Synchronization"Ra'Fat Al-Msie'deen
 
14- Process Synchronization.pptx
14- Process Synchronization.pptx14- Process Synchronization.pptx
14- Process Synchronization.pptxmobeenahmed49
 
Processscheduling 161001112521
Processscheduling 161001112521Processscheduling 161001112521
Processscheduling 161001112521marangburu42
 
Operating Systems - Process Synchronization and Deadlocks
Operating Systems - Process Synchronization and DeadlocksOperating Systems - Process Synchronization and Deadlocks
Operating Systems - Process Synchronization and DeadlocksMukesh Chinta
 
UNIT 2-UNDERSTANDING THE SYNCHRONIZATION PROCESS.pptx
UNIT 2-UNDERSTANDING THE SYNCHRONIZATION PROCESS.pptxUNIT 2-UNDERSTANDING THE SYNCHRONIZATION PROCESS.pptx
UNIT 2-UNDERSTANDING THE SYNCHRONIZATION PROCESS.pptxLeahRachael
 
Lecture 5- Process Synchonization_revised.pdf
Lecture 5- Process Synchonization_revised.pdfLecture 5- Process Synchonization_revised.pdf
Lecture 5- Process Synchonization_revised.pdfAmanuelmergia
 
Processscheduling 161001112521
Processscheduling 161001112521Processscheduling 161001112521
Processscheduling 161001112521marangburu42
 
Processscheduling 161001112521
Processscheduling 161001112521Processscheduling 161001112521
Processscheduling 161001112521marangburu42
 

Similar to Process Synchronization (20)

Lecture16-17.ppt
Lecture16-17.pptLecture16-17.ppt
Lecture16-17.ppt
 
Operating system 23 process synchronization
Operating system 23 process synchronizationOperating system 23 process synchronization
Operating system 23 process synchronization
 
Process synchronization
Process synchronizationProcess synchronization
Process synchronization
 
Lecture 5- Process Synchronization (1).pptx
Lecture 5- Process Synchronization (1).pptxLecture 5- Process Synchronization (1).pptx
Lecture 5- Process Synchronization (1).pptx
 
Mutual Exclusion using Peterson's Algorithm
Mutual Exclusion using Peterson's AlgorithmMutual Exclusion using Peterson's Algorithm
Mutual Exclusion using Peterson's Algorithm
 
CH05.pdf
CH05.pdfCH05.pdf
CH05.pdf
 
Process Synchronization -1.ppt
Process Synchronization -1.pptProcess Synchronization -1.ppt
Process Synchronization -1.ppt
 
6 Synchronisation
6 Synchronisation6 Synchronisation
6 Synchronisation
 
Critical section operating system
Critical section  operating systemCritical section  operating system
Critical section operating system
 
Process synchronizationfinal
Process synchronizationfinalProcess synchronizationfinal
Process synchronizationfinal
 
H04553942
H04553942H04553942
H04553942
 
Lecture 5 inter process communication
Lecture 5 inter process communicationLecture 5 inter process communication
Lecture 5 inter process communication
 
Operating Systems - "Chapter 5 Process Synchronization"
Operating Systems - "Chapter 5 Process Synchronization"Operating Systems - "Chapter 5 Process Synchronization"
Operating Systems - "Chapter 5 Process Synchronization"
 
14- Process Synchronization.pptx
14- Process Synchronization.pptx14- Process Synchronization.pptx
14- Process Synchronization.pptx
 
Processscheduling 161001112521
Processscheduling 161001112521Processscheduling 161001112521
Processscheduling 161001112521
 
Operating Systems - Process Synchronization and Deadlocks
Operating Systems - Process Synchronization and DeadlocksOperating Systems - Process Synchronization and Deadlocks
Operating Systems - Process Synchronization and Deadlocks
 
UNIT 2-UNDERSTANDING THE SYNCHRONIZATION PROCESS.pptx
UNIT 2-UNDERSTANDING THE SYNCHRONIZATION PROCESS.pptxUNIT 2-UNDERSTANDING THE SYNCHRONIZATION PROCESS.pptx
UNIT 2-UNDERSTANDING THE SYNCHRONIZATION PROCESS.pptx
 
Lecture 5- Process Synchonization_revised.pdf
Lecture 5- Process Synchonization_revised.pdfLecture 5- Process Synchonization_revised.pdf
Lecture 5- Process Synchonization_revised.pdf
 
Processscheduling 161001112521
Processscheduling 161001112521Processscheduling 161001112521
Processscheduling 161001112521
 
Processscheduling 161001112521
Processscheduling 161001112521Processscheduling 161001112521
Processscheduling 161001112521
 

More from Shipra Swati

Operating System-Process Scheduling
Operating System-Process SchedulingOperating System-Process Scheduling
Operating System-Process SchedulingShipra Swati
 
Operating System-Concepts of Process
Operating System-Concepts of ProcessOperating System-Concepts of Process
Operating System-Concepts of ProcessShipra Swati
 
Operating System-Introduction
Operating System-IntroductionOperating System-Introduction
Operating System-IntroductionShipra Swati
 
Fundamental of Information Technology - UNIT 8
Fundamental of Information Technology - UNIT 8Fundamental of Information Technology - UNIT 8
Fundamental of Information Technology - UNIT 8Shipra Swati
 
Fundamental of Information Technology - UNIT 7
Fundamental of Information Technology - UNIT 7Fundamental of Information Technology - UNIT 7
Fundamental of Information Technology - UNIT 7Shipra Swati
 
Fundamental of Information Technology - UNIT 6
Fundamental of Information Technology - UNIT 6Fundamental of Information Technology - UNIT 6
Fundamental of Information Technology - UNIT 6Shipra Swati
 
Fundamental of Information Technology
Fundamental of Information TechnologyFundamental of Information Technology
Fundamental of Information TechnologyShipra Swati
 

More from Shipra Swati (20)

Operating System-Process Scheduling
Operating System-Process SchedulingOperating System-Process Scheduling
Operating System-Process Scheduling
 
Operating System-Concepts of Process
Operating System-Concepts of ProcessOperating System-Concepts of Process
Operating System-Concepts of Process
 
Operating System-Introduction
Operating System-IntroductionOperating System-Introduction
Operating System-Introduction
 
Java unit 11
Java unit 11Java unit 11
Java unit 11
 
Java unit 14
Java unit 14Java unit 14
Java unit 14
 
Java unit 12
Java unit 12Java unit 12
Java unit 12
 
Java unit 7
Java unit 7Java unit 7
Java unit 7
 
Java unit 3
Java unit 3Java unit 3
Java unit 3
 
Java unit 2
Java unit 2Java unit 2
Java unit 2
 
Java unit 1
Java unit 1Java unit 1
Java unit 1
 
OOPS_Unit_1
OOPS_Unit_1OOPS_Unit_1
OOPS_Unit_1
 
Ai lab manual
Ai lab manualAi lab manual
Ai lab manual
 
Fundamental of Information Technology - UNIT 8
Fundamental of Information Technology - UNIT 8Fundamental of Information Technology - UNIT 8
Fundamental of Information Technology - UNIT 8
 
Fundamental of Information Technology - UNIT 7
Fundamental of Information Technology - UNIT 7Fundamental of Information Technology - UNIT 7
Fundamental of Information Technology - UNIT 7
 
Fundamental of Information Technology - UNIT 6
Fundamental of Information Technology - UNIT 6Fundamental of Information Technology - UNIT 6
Fundamental of Information Technology - UNIT 6
 
Fundamental of Information Technology
Fundamental of Information TechnologyFundamental of Information Technology
Fundamental of Information Technology
 
Disk Management
Disk ManagementDisk Management
Disk Management
 
File Systems
File SystemsFile Systems
File Systems
 
Memory Management
Memory ManagementMemory Management
Memory Management
 
Deadlocks
DeadlocksDeadlocks
Deadlocks
 

Recently uploaded

Choosing the Right CBSE School A Comprehensive Guide for Parents
Choosing the Right CBSE School A Comprehensive Guide for ParentsChoosing the Right CBSE School A Comprehensive Guide for Parents
Choosing the Right CBSE School A Comprehensive Guide for Parentsnavabharathschool99
 
ENGLISH 7_Q4_LESSON 2_ Employing a Variety of Strategies for Effective Interp...
ENGLISH 7_Q4_LESSON 2_ Employing a Variety of Strategies for Effective Interp...ENGLISH 7_Q4_LESSON 2_ Employing a Variety of Strategies for Effective Interp...
ENGLISH 7_Q4_LESSON 2_ Employing a Variety of Strategies for Effective Interp...JhezDiaz1
 
4.18.24 Movement Legacies, Reflection, and Review.pptx
4.18.24 Movement Legacies, Reflection, and Review.pptx4.18.24 Movement Legacies, Reflection, and Review.pptx
4.18.24 Movement Legacies, Reflection, and Review.pptxmary850239
 
ISYU TUNGKOL SA SEKSWLADIDA (ISSUE ABOUT SEXUALITY
ISYU TUNGKOL SA SEKSWLADIDA (ISSUE ABOUT SEXUALITYISYU TUNGKOL SA SEKSWLADIDA (ISSUE ABOUT SEXUALITY
ISYU TUNGKOL SA SEKSWLADIDA (ISSUE ABOUT SEXUALITYKayeClaireEstoconing
 
GRADE 4 - SUMMATIVE TEST QUARTER 4 ALL SUBJECTS
GRADE 4 - SUMMATIVE TEST QUARTER 4 ALL SUBJECTSGRADE 4 - SUMMATIVE TEST QUARTER 4 ALL SUBJECTS
GRADE 4 - SUMMATIVE TEST QUARTER 4 ALL SUBJECTSJoshuaGantuangco2
 
What is Model Inheritance in Odoo 17 ERP
What is Model Inheritance in Odoo 17 ERPWhat is Model Inheritance in Odoo 17 ERP
What is Model Inheritance in Odoo 17 ERPCeline George
 
Earth Day Presentation wow hello nice great
Earth Day Presentation wow hello nice greatEarth Day Presentation wow hello nice great
Earth Day Presentation wow hello nice greatYousafMalik24
 
INTRODUCTION TO CATHOLIC CHRISTOLOGY.pptx
INTRODUCTION TO CATHOLIC CHRISTOLOGY.pptxINTRODUCTION TO CATHOLIC CHRISTOLOGY.pptx
INTRODUCTION TO CATHOLIC CHRISTOLOGY.pptxHumphrey A Beña
 
Keynote by Prof. Wurzer at Nordex about IP-design
Keynote by Prof. Wurzer at Nordex about IP-designKeynote by Prof. Wurzer at Nordex about IP-design
Keynote by Prof. Wurzer at Nordex about IP-designMIPLM
 
Science 7 Quarter 4 Module 2: Natural Resources.pptx
Science 7 Quarter 4 Module 2: Natural Resources.pptxScience 7 Quarter 4 Module 2: Natural Resources.pptx
Science 7 Quarter 4 Module 2: Natural Resources.pptxMaryGraceBautista27
 
Computed Fields and api Depends in the Odoo 17
Computed Fields and api Depends in the Odoo 17Computed Fields and api Depends in the Odoo 17
Computed Fields and api Depends in the Odoo 17Celine George
 
Proudly South Africa powerpoint Thorisha.pptx
Proudly South Africa powerpoint Thorisha.pptxProudly South Africa powerpoint Thorisha.pptx
Proudly South Africa powerpoint Thorisha.pptxthorishapillay1
 
Like-prefer-love -hate+verb+ing & silent letters & citizenship text.pdf
Like-prefer-love -hate+verb+ing & silent letters & citizenship text.pdfLike-prefer-love -hate+verb+ing & silent letters & citizenship text.pdf
Like-prefer-love -hate+verb+ing & silent letters & citizenship text.pdfMr Bounab Samir
 
ACC 2024 Chronicles. Cardiology. Exam.pdf
ACC 2024 Chronicles. Cardiology. Exam.pdfACC 2024 Chronicles. Cardiology. Exam.pdf
ACC 2024 Chronicles. Cardiology. Exam.pdfSpandanaRallapalli
 
HỌC TỐT TIẾNG ANH 11 THEO CHƯƠNG TRÌNH GLOBAL SUCCESS ĐÁP ÁN CHI TIẾT - CẢ NĂ...
HỌC TỐT TIẾNG ANH 11 THEO CHƯƠNG TRÌNH GLOBAL SUCCESS ĐÁP ÁN CHI TIẾT - CẢ NĂ...HỌC TỐT TIẾNG ANH 11 THEO CHƯƠNG TRÌNH GLOBAL SUCCESS ĐÁP ÁN CHI TIẾT - CẢ NĂ...
HỌC TỐT TIẾNG ANH 11 THEO CHƯƠNG TRÌNH GLOBAL SUCCESS ĐÁP ÁN CHI TIẾT - CẢ NĂ...Nguyen Thanh Tu Collection
 
ECONOMIC CONTEXT - PAPER 1 Q3: NEWSPAPERS.pptx
ECONOMIC CONTEXT - PAPER 1 Q3: NEWSPAPERS.pptxECONOMIC CONTEXT - PAPER 1 Q3: NEWSPAPERS.pptx
ECONOMIC CONTEXT - PAPER 1 Q3: NEWSPAPERS.pptxiammrhaywood
 
call girls in Kamla Market (DELHI) 🔝 >༒9953330565🔝 genuine Escort Service 🔝✔️✔️
call girls in Kamla Market (DELHI) 🔝 >༒9953330565🔝 genuine Escort Service 🔝✔️✔️call girls in Kamla Market (DELHI) 🔝 >༒9953330565🔝 genuine Escort Service 🔝✔️✔️
call girls in Kamla Market (DELHI) 🔝 >༒9953330565🔝 genuine Escort Service 🔝✔️✔️9953056974 Low Rate Call Girls In Saket, Delhi NCR
 
DATA STRUCTURE AND ALGORITHM for beginners
DATA STRUCTURE AND ALGORITHM for beginnersDATA STRUCTURE AND ALGORITHM for beginners
DATA STRUCTURE AND ALGORITHM for beginnersSabitha Banu
 

Recently uploaded (20)

Choosing the Right CBSE School A Comprehensive Guide for Parents
Choosing the Right CBSE School A Comprehensive Guide for ParentsChoosing the Right CBSE School A Comprehensive Guide for Parents
Choosing the Right CBSE School A Comprehensive Guide for Parents
 
LEFT_ON_C'N_ PRELIMS_EL_DORADO_2024.pptx
LEFT_ON_C'N_ PRELIMS_EL_DORADO_2024.pptxLEFT_ON_C'N_ PRELIMS_EL_DORADO_2024.pptx
LEFT_ON_C'N_ PRELIMS_EL_DORADO_2024.pptx
 
ENGLISH 7_Q4_LESSON 2_ Employing a Variety of Strategies for Effective Interp...
ENGLISH 7_Q4_LESSON 2_ Employing a Variety of Strategies for Effective Interp...ENGLISH 7_Q4_LESSON 2_ Employing a Variety of Strategies for Effective Interp...
ENGLISH 7_Q4_LESSON 2_ Employing a Variety of Strategies for Effective Interp...
 
4.18.24 Movement Legacies, Reflection, and Review.pptx
4.18.24 Movement Legacies, Reflection, and Review.pptx4.18.24 Movement Legacies, Reflection, and Review.pptx
4.18.24 Movement Legacies, Reflection, and Review.pptx
 
ISYU TUNGKOL SA SEKSWLADIDA (ISSUE ABOUT SEXUALITY
ISYU TUNGKOL SA SEKSWLADIDA (ISSUE ABOUT SEXUALITYISYU TUNGKOL SA SEKSWLADIDA (ISSUE ABOUT SEXUALITY
ISYU TUNGKOL SA SEKSWLADIDA (ISSUE ABOUT SEXUALITY
 
GRADE 4 - SUMMATIVE TEST QUARTER 4 ALL SUBJECTS
GRADE 4 - SUMMATIVE TEST QUARTER 4 ALL SUBJECTSGRADE 4 - SUMMATIVE TEST QUARTER 4 ALL SUBJECTS
GRADE 4 - SUMMATIVE TEST QUARTER 4 ALL SUBJECTS
 
What is Model Inheritance in Odoo 17 ERP
What is Model Inheritance in Odoo 17 ERPWhat is Model Inheritance in Odoo 17 ERP
What is Model Inheritance in Odoo 17 ERP
 
TataKelola dan KamSiber Kecerdasan Buatan v022.pdf
TataKelola dan KamSiber Kecerdasan Buatan v022.pdfTataKelola dan KamSiber Kecerdasan Buatan v022.pdf
TataKelola dan KamSiber Kecerdasan Buatan v022.pdf
 
Earth Day Presentation wow hello nice great
Earth Day Presentation wow hello nice greatEarth Day Presentation wow hello nice great
Earth Day Presentation wow hello nice great
 
INTRODUCTION TO CATHOLIC CHRISTOLOGY.pptx
INTRODUCTION TO CATHOLIC CHRISTOLOGY.pptxINTRODUCTION TO CATHOLIC CHRISTOLOGY.pptx
INTRODUCTION TO CATHOLIC CHRISTOLOGY.pptx
 
Keynote by Prof. Wurzer at Nordex about IP-design
Keynote by Prof. Wurzer at Nordex about IP-designKeynote by Prof. Wurzer at Nordex about IP-design
Keynote by Prof. Wurzer at Nordex about IP-design
 
Science 7 Quarter 4 Module 2: Natural Resources.pptx
Science 7 Quarter 4 Module 2: Natural Resources.pptxScience 7 Quarter 4 Module 2: Natural Resources.pptx
Science 7 Quarter 4 Module 2: Natural Resources.pptx
 
Computed Fields and api Depends in the Odoo 17
Computed Fields and api Depends in the Odoo 17Computed Fields and api Depends in the Odoo 17
Computed Fields and api Depends in the Odoo 17
 
Proudly South Africa powerpoint Thorisha.pptx
Proudly South Africa powerpoint Thorisha.pptxProudly South Africa powerpoint Thorisha.pptx
Proudly South Africa powerpoint Thorisha.pptx
 
Like-prefer-love -hate+verb+ing & silent letters & citizenship text.pdf
Like-prefer-love -hate+verb+ing & silent letters & citizenship text.pdfLike-prefer-love -hate+verb+ing & silent letters & citizenship text.pdf
Like-prefer-love -hate+verb+ing & silent letters & citizenship text.pdf
 
ACC 2024 Chronicles. Cardiology. Exam.pdf
ACC 2024 Chronicles. Cardiology. Exam.pdfACC 2024 Chronicles. Cardiology. Exam.pdf
ACC 2024 Chronicles. Cardiology. Exam.pdf
 
HỌC TỐT TIẾNG ANH 11 THEO CHƯƠNG TRÌNH GLOBAL SUCCESS ĐÁP ÁN CHI TIẾT - CẢ NĂ...
HỌC TỐT TIẾNG ANH 11 THEO CHƯƠNG TRÌNH GLOBAL SUCCESS ĐÁP ÁN CHI TIẾT - CẢ NĂ...HỌC TỐT TIẾNG ANH 11 THEO CHƯƠNG TRÌNH GLOBAL SUCCESS ĐÁP ÁN CHI TIẾT - CẢ NĂ...
HỌC TỐT TIẾNG ANH 11 THEO CHƯƠNG TRÌNH GLOBAL SUCCESS ĐÁP ÁN CHI TIẾT - CẢ NĂ...
 
ECONOMIC CONTEXT - PAPER 1 Q3: NEWSPAPERS.pptx
ECONOMIC CONTEXT - PAPER 1 Q3: NEWSPAPERS.pptxECONOMIC CONTEXT - PAPER 1 Q3: NEWSPAPERS.pptx
ECONOMIC CONTEXT - PAPER 1 Q3: NEWSPAPERS.pptx
 
call girls in Kamla Market (DELHI) 🔝 >༒9953330565🔝 genuine Escort Service 🔝✔️✔️
call girls in Kamla Market (DELHI) 🔝 >༒9953330565🔝 genuine Escort Service 🔝✔️✔️call girls in Kamla Market (DELHI) 🔝 >༒9953330565🔝 genuine Escort Service 🔝✔️✔️
call girls in Kamla Market (DELHI) 🔝 >༒9953330565🔝 genuine Escort Service 🔝✔️✔️
 
DATA STRUCTURE AND ALGORITHM for beginners
DATA STRUCTURE AND ALGORITHM for beginnersDATA STRUCTURE AND ALGORITHM for beginners
DATA STRUCTURE AND ALGORITHM for beginners
 

Process Synchronization

  • 1. Unit IV Process Synchronization 4.1 Background The processes may execute either independently or in cooperating way. In the later case, processes share data with other processes and hence gets afftected by their execution too. The reason for providing process cooperation: • Information sharing: Since several users may be interested in the same piece of information (for instance, a shared file), we must provide an environment to allow concurrent access to such information. • Computation speed: If we want a particular task to run faster, we must break it into subtasks, each of which will be executing in parallel with the others. Notice that such a speedup can be achieved only if the computer has multiple processing elements (such as CPUs or I/O channels). • Modularity: We may want to construct the system in a modular fashion, dividing the system functions into separate processes or threads. • Convenience: Even an individual user may work on many tasks at the same time. For instance, a user may be editing, printing, and compiling in parallel. Cooperating processes require an interprocess communication (IPC) mechanism for exchanging data and information. Following is the two fundamental models of IPC:- 1. Shared memory: A region of memory that is shared by cooperating process is created. Processes can exchange information by reading and writing data to the shared region. 2. Message Passing: It require system calls for every message exchange. In simple terms standard message is passed among the processes for communication to take place. Two primitives message can be thought of under this scheme: • send (destination, &message) • receive (source, &message)
  • 2. Comparision of shared memory and messgae passing schemes: • Shared memory is faster once it is set up because no system calls are required and read/write operation occurs at normal speed. • As message passing requires system calls for every message transfer, it is slower. • In comparision to shared memory, message passing is easier to implement because no new place is created for message sharing. Example Problem: Producer-Consumer Problem The code for the producer process can be defined as follows: An integer variable counter, initialized to 0. counter is incremented every time we add a new item to the buffer and is decremented every time we remove one item from the buffer. The code for the consumer process can be defined as follows: Although both the producer and consumer routines shown above are correct separately, they may not function correctly when executed concurrently. For example, suppose that the value of the variable counter is currently 5 and that the producer and consumer processes execute the statements
  • 3. "counter++" and "counter--" concurrently. Following the execution of these two statements, the value of the variable counter may be 4, 5, or 6! The only correct result, though, is counter == 5, which is generated correctly if the producer and consumer execute separately. We can show that the value of counter may be incorrect as follows. Note that the statement" counter++" may be implemented in machine language (on a typical machine) as: register1 = counter register1 = register1 + 1 counter = register1 Similarly, the statement "counter--" is implemented as follows: register2 = counter register2 = register2 - 1 counter= register2 where register1 and register2 are local CPU registers. The concurrent execution of "counter++" and "counter--" is equivalent to a sequential execution in which the lower-level statements presented previously are interleaved in some arbitrary order. One such interleaving is: Notice that we have 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". Race Condition We would arrive at this incorrect state because we allowed both processes to manipulate the variable counter concurrently. A situation like this, 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 Race Condition. To guard against the race condition above, we need to ensure that only one process at a time can manipulate the variable counter. So, we require that the processes be synchronized in some way. 4.2 critical section problem Consider a system consisting of n processes {Po, P1 , ... , Pn-1}. Each process has a segment of code, in which they are changing common variables. This piece of code is called critical section. The important feature of the system is that, when one process is executing in its critical section, no other process is to be allowed to execute in its critical section. That is, no two processes are executing in their critical sections at the same time. The critical-section problem gives a protocol that the processes can use to cooperate. The general structure of a typical process Pi is shown in following figure. The entry section and exit section are enclosed in boxes to highlight these important segments of code.
  • 4. Each process must request permission to enter its critical section. The section of code implementing this request is the entry section. critical section may be followed by an exit section. The remaining code is the remainder section. A solution to the critical-section problem must satisfy the following three requirements: 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 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 carmot be postponed indefinitely. 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 is granted. Peterson's solution A classic software-based solution to the critical-section problem is Peterson's solution. In modern computer architectures, there are no guarantees that Peterson's solution will work correctly. However the solution is presented because it 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 P0 and P1. For convenience, if the current process is referred as Pi, we use Pj to denote the other process; that is, j = 1 - i. Peterson's solution requires the two processes to share two data items: • int turn; The variable turn indicates whose turn it is to enter its critical section. That is, if turn == i, then process Pi is allowed to execute in its critical section. • boolean flag[2]; The flag array is used to indicate if a process is ready to enter its critical section. For example, if flag [i] is true, this value indicates that Pi is ready to enter its critical section. 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 (i.e. j) 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.
  • 5. But 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. Proof of the correctness of this solution We need to show that: • Mutual exclusion is preserved. • The progress requirement is satisfied. • The bounded-waiting requirement is met. To prove property 1, we note that each Pi enters its critical section only if either flag [j] == false or turn == i [(while flag[j] && turn == j)]. Also note that, if both processes can be executing in their critical sections at the same time, then flag [0] ==flag [1] ==true. These two observations imply that P0 and P1 could not have successfully executed their while statements at about the same time, since the value of turn can be either 0 or 1 but can not be both. Hence, one of the processes -say, Pj -must have successfully executed the while statencent, whereas Pi had to execute at least one additional statement ("turn== j"). However, at that time, flag [j] == true and turn == j, and this condition will persist as long as Pi is in its critical section; as a result, mutual exclusion is preserved. To prove property 2, we note that a process Pi can be prevented from entering the critical section only if it is stuck in the while loop with the condition flag [j] ==true and turn== j. If Pj is not ready to enter the critical section, then flag [j] ==false, and Pi can enter its critical section. If Pj has set flag [j] to true and is also executing in its while statement, then either turn == i or turn == j. If turn == i, then Pi will enter the critical section. If turn== j, then Pj will enter the critical section. However, once Pi exits its critical section, it will reset flag [j] to false, allowing Pi to enter its critical section. To prove property 3, If Pj resets flag [j] to true, it must also set turn to i. Thus, since Pi does not change the value of the variable turn while executing the while statement, Pi will enter the critical section (progress) after at most one entry by Pj (bounded waiting). 4.3 Synchronization Hardware Software-based solutions such as Peterson's are not guaranteed to work on modern computer architectures. Instead, a process must acquire a lock before entering a critical section and it releases
  • 6. the lock when it exits the critical section as illustrated in following Figure. In Figure 6.8, we present another algorithm using the TestAndSet () instruction that satisfies all the critical-section requirements. TestAndSet () is hardware supported atomic instruction i.e. it can't be interrupted once it has started running. The common data structures are boolean waiting[n]; boolean lock; These data structures are initialized to false.
  • 7. To prove that the mutual-exclusion requirement is met, we note that process Pi can enter its critical section only if either waiting [i] == false or key == false. The value of key can become false only if the TestAndSet () is executed. The first process to execute the TestAndSet () will find key== false; all others must wait. The variable waiting [i] can become false only if another process leaves its critical section; only one waiting [i] is set to false, maintaining the mutual-exclusion requirement. To prove that the progress requirement is met, we note that the arguments presented for mutual exclusion also apply here, since a process exiting the critical section either sets lock to false or sets waiting[j] to false. Both allow a process that is waiting to enter its critical section to proceed. To prove that the bounded-waiting requirement is met, we note that, when a process leaves its critical section, it scans the array waiting in the cyclic ordering (i + 1, i + 2, ... , n - 1, 0, ... , i - 1). It designates the first process in this ordering that is in the entry section (waiting[j] ==true) as the next one to enter the critical section. Any process waiting to enter its critical section will thus do so within n - 1 turns. 4.4 Semaphores The hardware-based solution to the critical-section problem (TestAndSet) are complicated for application programmers to use. So, we use a synchronization tool called semaphore. A semaphore S is an integer variable that, apart from initialization, is accessed only through two standard atomic operations: wait () and signal (). The wait () operation was originally termed P (from the Dutch proberen, "to test"); signal() was originally called V (from verhogen, "to increment"). The definition of wait () is as follows: The definition of signal() is as follows: 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. In addition, in the case of wait (S), the testing of the integer value of S (S <= 0), as well as its possible modification (S--), must be executed without interruption. Usage There are two types of semaphores: Binary semaphore and Counting semaphore. Binary Semaphore can have value 0 and 1 only, so sometimes they are also called as mutex locks, as they are locks that provide mutual exclusion. We can use binary semaphores to deal with the critical-section problem for multiple processes. The
  • 8. n processes share a semaphore, mutex, initialized to 1. Each process Pi is organized as shown in Figure 6.9. Counting semaphores can be used to control access to a given resource consisting of a finite number of instances. 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 (thereby decrementing the count). When a process releases a resource, it performs a signal() operation (incrementing the count). 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. We can also use semaphores to solve various synchronization problems. For example, consider two concurrently running processes: P1 with a statement S1 and P2 with a statement S2 . Suppose we require that S2 be executed only after S1 has completed. We can implement this scheme readily by letting P1 and P2 share a common semaphore synch, initialized to 0, and by inserting the statements S1 ; signal(synch) ; in process P1 and the statements wait(synch); S2 ; in process P2. Because synch is initialized to 0, P2 will execute S2 only after P1 has invoked signal (synch), which is after statement S1 has been executed.