Download as pdf or txt
Download as pdf or txt
You are on page 1of 24

College of Computer and lnfm·mation Systems

Department of Computer Science


University of Umm Al-Qura

14012203-4: Operating Systems


First Term: 2022/23

Chapter 6:

------,, Process Synchronization


We use the term process as a generic
term for both a process and a thread

DI'. Abdulbaset Gaddah


aagaddab@nqn.edu .sa

Objectives
"
❖ Discuss basic concepts related to concurrency, such as:
■ Race condition
■ Mutual exclusion
■ Critical-section problem
• Requirements for critical-section problem solutions

❖ Present both software and hardware solutions of the critical-section


problem
■ Peterson's Solution
■ Synchronization Hardware
■ Semaphores

❖ Explore classical problems in process synchronization


■ Producer/Consumer Problem
■ Dining-Philosophers Problem

Operating Systems - Dr. .Abdulbaset Gaddah

gesoursse
Operating Systems - Dr. Abdulbaset Gaddah ,,,,,, ..., ~ need synctonization 1
Multiple Processes
'
'-...,/

❖ The central themes of operating system design are all concerned


with the management of processes and threads

❖ Can be classified broadly into t hree categories:


■ Multiprogramming: multiple processes wjthin a A.j niprocessod svstem .
■ Multiprocessing : multiple processes within a multiprocessor system
I
■ Distributed Processing: multiple processes executing on multiple,
£.a1s_!nbuted)computer systems

❖ Al l of these involve competition , cooperation, and communication


among processes that may run in real or pseudo parallelism mode

❖ Big issue is concurrency


■ Managing the interaction of all of these processes

Operati ng Syste ms - Dr: Abdulbaset Gaddah

3
I

Principles of Concurrency
❖ Concurrency is a concept where multiple processes or t hreads ru n
simultaneously in uniprocessor QLmulti processor systems
❖ Interleaving and overlapping execution can be viewed as examples
of concurrent processing, and both present the same problems
❖ the relative speed of execution of processes f annot be predicted}
■ Depends on activities of other processes,
■ The way the OS handles interrupts, and
■ Scheduling policies of t he OS

Process 1 Process 1

Process 2 Process 2
Process 3 ~1'/,~m::;J
1/ _ __
(A) Interleavi ng (multlprogrammin 11processor) (B ) lni erl eaving & overlapping (rmultiprocessin
hot mote
Operati ng Syste ms - Dr. .Abdulbaset Gadda h 4

Operating Systems - Dr. Abdulbaset Gaddah 2


Difficulties of Concurrency
'
'-.._,/ - ---
❖ Sharing of global resources safely is difficult
■ Iwo processes access the same global variable, and both perform reads
and writes on that variable? may result in data inconsistency

❖ ADocation of resources optimally is difficult


■ A process is allocated an I/O channel and then is suspended before using
that channel? may lead to a deadllock condition

❖ Programming errors is difficult to locate, because the contexts in


which errors occur cannot always be reproduced easily

Operati ng Systems - Dr. Abdulbaset Gaddah

Race condition
- - ----------
ls JIJ fr
{' ~~
❖ Race condition occurs when multiple processes (or threads) access
and manipulate (read and write) the same data items concurrently
❖ The final result depends on the execut1
ion order of the processes
■ The output depends on who finishes t he race last

❖ May result fn data inconsistency


❖ Maintainin · ion to
ensure th late
the share aa J,
Cc,urrt.U
ntil it ffin\ ri/isS"h~ esS ddeU\[
It Q.
alitnng8 w ith
wit- ",
ith~e11. g, l1.
ob~~1al v\1-i,arr·{\b
iable
le
e nfldt is.s"
ot ffint,,i h ti:.~
he
w holee prr.c.e..s-rJ
'--'~o\e rocess
Operati ng Systems - Dr. Abdulbaset Gaddah 6

Operating Systems - Dr. Abdulbaset Gaddah 3


A Simple Example ace condition w
ra
Process A A register Process B

switch t
beforewrite

We had arrived at this incorrect state because we allowed


both processes to manipulate the variable M concurrently

Operating Systems - Dr. Abdulbaset Gaddah 7

Th
T e s'>1Jt1c.
lit. eals w
ync d~,-..,\s ith cCrH:-ic.-..,
wi\.ti ritical sr,c..1.f
ectioann o011b
nly
sh
harre
es
Aq-._,sdata ~ J,.~
~'-ii' h .a_.&11 m
"
ss-~
e
The Cr1tica I Section Problem
•!{Critical sectionl- a section of code within a rocess that mani ulates
shared data or resource, n ,t cannot be executed concurren

❖ The execution of critical sections must be mutually exclusive : at any


time~ nly one process] is allowed to execute in its critical section
( even with multi ple CPUs)

❖ The critical section problem is to design a protocol to solve this


■ UiaLis, no two processes are executing in their critical sections at the
~ame tjme

Operating Systems - Dr. .Abdulbaset Gaddah 8

Operating Systems - Dr. Abdulbaset Gaddah 4


The Critical Section Problem (Cont.)
Ask for


For the critical section problem solution:

Each processfm ust request a permission \


- do {

entry sectiin
,,
,.
,r
,'
,
The protocol
for ME

to enter its critical section


Shared data '
"==;;;;;;;,;;;;;=;;;:.,1 ~. critical section :
I
❖ The section of code im · this I
I

request is the entry se I

exit section ◄ - - -------~

❖ The critical section might be followed by


remainder section
I
an exit section to l1\~ar...,
to in
n form -b~c\.:b
that rt' c\ofl IL
it'sdone
} while (TRUE);
❖ The remainder code is the remainder
section
I General structure of a process P;

Operating Systems - Dr: Abdu lbaset Gaddah 9

Requ1r,e ments for the Critical Section Problem


❖ A solution to the critical section problem must satisfy the following
three regujrements:
•• Mutual Exclusion
■ If process P1 is executing in its critical section, then no other processes
can be executing in their critical sections
) :. Progress
■ If no process is in its critical section and some processes wish to enter
thejr crjtjcal sectjons. then only those processes that are not in their
reminder sections can participate in the decision on which will enter its
critical section next, and this selection cannot be.,postponed iJdefinitely

❖ Bounded Waiting ...-.....-:---~_.. §s >I ; ~ lI


■ There is a bound, or limit, on the umber of t ime that other processes
are allowed to enter their critical sections er a process has ma

L o
frequest to ente~ its critical section and before that request is granted

Operating Systems - Dr. .Abdulbaset Gaddah 10

10

Operating Systems - Dr. Abdulbaset Gaddah 5


Types of Solutions
'
❖ Software solution: algorithms whose correctness does not rely on
any other assumptions other than positive processing speed
■Cjeterson'salgorithm\
I 1/f _1 P, e. .t~t·u.-,'s
ME
erson's '1.,urll~,., h CLht\J Jw"'-.r(
allgorithm is
s ahardware
❖ Hardware solution : rely on some special machine 'instructions
sSool\ti10
ution11

■ TSL (Test and Set Lock) instructions set

❖ Operation System solution: provide some functions and data


structures to the programmer
■ Semaphores

r
Operating Systems - Dr. Abdulbaset Gaddah

11

Algorithm 1 - Incorrect
int turn = i; // shared control variable

Pi: Pj:
while (t " != i) ; /* busy wait*/ while u n != j);
CS; C;
turn = j; turn= i;
RS; RS;

❖ Guarantees mutual ex~I "sion


❖ Does not guaranteeDrogress - since it enfor strict alternation of
processes en etfng CSs 1

■ E er enter it
❖ Bo.u I mg v10 a e - suppose o process terminates nile its
A~
Operating Systems • Dr. .Abdulbaset Gaddah
----- ~
12

12

Operating Systems - Dr. Abdulbaset Gaddah 6


Algorithm 2 - Incorrect
- -- -
boolean flag[2] = {false, false} //flag[i] indicates that Pi is in it S

Pi: Pj:
flag [i] = ri.te; /* wish to enter cs */ flag[j] :;,{rue;
while (flag[j]), · /* busy wait*/ wh ·1~ag [i]) ;
CS; S;
flag[i] = false; */ flag[j] = false;
RS; RS;

❖ G• 1arantees Q!_LltuqJ, xclusion


❖ Violates progr..e(s - both processes could set flag · --true and then
deadlo~Von the w1iile ~
❖-Boyrrded waiting violated
/
Operating Systems - Dr: Abdu lbaset Gaddah 13

13

Peterson's Algorithm

❖ Is restricted to two processes that alternate execution between


their critical section and remainder sections
■ The processes are called Pi and PL

❖ Requires two data items to be shared between the two processes:


int turn ·
boolean flag [ 2 ] ;

■ ~ rn indicates jyhose turn/it is to enter the critical! section

• flag [ i] =
a
■ f l a g is used to indicate if a process isffi!aciy}to enter the critical section
true implies that process Pi is ready!

Operating Systems - Dr. .Abdulbaset Gaddah 14

14

Operating Systems - Dr. Abdulbaset Gaddah 7


Peterson's Algorithm (Cont.)
'
❖ The Peterson's solution for process Pi and Pj
❖ Initial ization:
boolean flag[2] = { false, false };
int turn= i or j;

structure of process Pi structure of process Pj


do I do {
r - - - - - - - - - - - Entry Section -, r-- - - - - - - - -- Entry Section -,
1
flag(i] = true; I
1
flag[j] = true; I

I turn = j; I I turn = i; I
I wh.ile (flag[j] && turn == j); I ~ while (flag[i]_ && _ turn == i); I
L - - - - - - - - - - - - - - - - - _I
CRITICAL SECTION CRITICAL SECTION

flag[i] = false;
Exit Section J flag[j] = false;
Exit Section J
REMAINDER SECTION REMAINDER SECTION

while (true) ; while (true) ;

,v
Operating Systems - Dr: Abdulbaset Gaddah 15

15

Proof of Correctness
\.. , /

❖ To proof the algorithm's correctness, we need to show :


❖ The mutual exclusion is preserved:
■ Pi and Pj are both in critical section only if flag[i] = flagfj] = true and
only if turn = i or j for both Pi and Pj (impossible)

❖ The progress requirement is satisfied :


■ Case 1: E
• Pi is ready to enter its critical section flag[i] == true
• If Pj is not ready to enter its critical section then flag [j] = = false, and Pi can
enter its critical section ....
---....... Case 2:
• Pi and Pj are both ready to enter the critical sect ion flag[i] == flag[j] == true
• Eirther turn== i or turn== j
• If turn = = i, then Pi will enter t he critical section
• If turn == j, then Pj will enter the cnltical section
'-V
Operati ng Systems - Dr. .Abdulbaset Gaddah 16

16

Operating Systems - Dr. Abdulbaset Gaddah 8


Proof of Correctness (Cont.)
'
❖ The bounded-waiting requirement is satisfied:
■ Once Pj exits its critical section, it will reset flag[j] to false, allowing Pi
to enter its cnt1cal section
■ .t=ven if Pj immediately resets fllag[il to true. jt must ajso set turn to i
■ ~ Pi will enter the critical section a~erla't most onf{ entry by Pj

Operating Systems - Dr. Abdulbaset Gaddah

17

Disadvantages of Peterson's Solution


'
❖ Processes that are requesting to enter in their critical section are
busy waiting (consuming processor time needlessly)

❖ It is limited rOtwo processeg

'-V
Operating Systems - Dr. .Abdulbaset Gaddah 18

18

Operating Systems - Dr. Abdulbaset Gaddah 9


Hardware Solution
❖ We can state that any solution to the critical-section problem is
based on idea of locking (protecting critical regions via locks)

■ -
A process must acquire a lock before enterfng a critical section
It releases the lock when It exits the critical section

do (
acquire lock
c ri t i cal section
release lock
remainder section
whi l e (TRUE);

❖ Here, we follow the above concept and explore solutions to the


critical-section problem using hardware techniques

Operating Systems - Dr. Abdu lbaset Gaddah

19

Interrupt Disabling ...,~.! ~


so d~is,LI"~,._,,
isable saw /1,!.
CPU
a
D
ÉME oCcfsf iss
'-) - -- -~'-"~of~ J, t.PU .ts..-.
❖ On a Uniprocessor :
S
■ mutua l exclusion is preserved but the
efficiency of execution is degraded : ~
~ we cannot interleave execution
with other processes that are in RS Process Pi:
repeat
❖ Ona Multiprocessor:
disable interrupts
■ mutua l exclusion is not preseryed : CS is
now atomic but not mutually exclusive critical s ection
(interrupts are not disabled on other
enable interrupts
processors)
remainder section
■ will not work in a multiprocessor
architecture fo rever

❖ Generally, not an acceptable solution

'-V
Operating Systems - Dr. .Abdulbaset Gaddah 20

20

Operating Systems - Dr. Abdulbaset Gaddah 10


Special Hardware Instructions att.e
4\.. om
"" i;c'! gv,g Al b 1. !P ~ ~
I
❖ Uniprocessors - could disable interrupts lI\ ut- t "'"V It Lo
.r!. --.aid
❖ Multiprocessors - no interrupt mechanism between processors on
which mutual exclusion can be based

❖ Modern machines provide wecial atomic hardwar(instruction!\ T


■ Atomic ➔ uninterruptible or indivisibly i J W
❖ We will look at two kinds of hardware instructions:
E W
:fS.,_., 1,1 - ---~ Em I
The atomic Test and set instruction int
" - . The atomic Swap instruction

❖ erovide mutual exclusion but need more complex algorithms for


satisfying the other requirements of the CS problem: progress and
bounded waiti ng

Operating Systems - Dr. Abdulbaset Gaddah 21

21

The test-and-set Instruction


❖ Test and set (modify) the content of a word, atomically
boolean TestAndSet (boolean *tai:get)
{
boolean rv = *target ;
*target= TRUE ;
return rv ;
AC++ descri tion of tesl-and•set
en Proc
Proc
Proces
esse
ses
ses
❖ We can implement "mutual exclusion" by declaring a shared~ oolean
cloeCle,.
variable lock, initialized to false ~\ ck ,-;:
is -fh!:.~~
the
❖ Then the structure of proGess Pi is: Ibm
do {
O '.L ,-. \ ,
was tJ ex✓
while ( TestAndSet @ ock) );
critical section U--,G
\ -

~~ - - -

~
I .J~t•-.,
.,-, ~ C...

lock = FALSE; "9 irf e-c.- J '


rema i nde r sect i on ~
} while (TRUE) ;

Operating Systems - Dr. .Abdulbaset Gaddah 22

22

Operating Systems - Dr. Abdulbaset Gaddah 11


Swap (XCHG Instruction)
the content of two words, atomically
void swap {boolean *a, bool ean *bl
I l•c.tc~\-r.-..::,
boolean temp= *a ;
*a = "b;
*b = temp ; 739
I AC ++ description of swap

❖ We can implement '\mutual exclusion" by declaring a shared Boo~ean


variable lock, initialized to false
❖ Then th~ st;11cture of process Pi is: l }J f Ibm
0

IN Any 24
key = TRUE; \
while (key == TRUE)
Swap ( &loclc, &key ) ;
1J.a') t. '/
~

ci;itical sectiori
lock= FALSE;
remaindei; section
} wh il e ( TRUE ) ;

Operating Systems - Dr: Abdu lbaset Gaddah 23

23

Disadvantages of Special Hardware Instructions


"
'-.,/ ♦:♦ Busy-waiting is employed Cw
C '4J"'hH,
ile d~o{"lj
oing LLo-or1
oop
■ While a process is waiting for access to a critical section it continues to
consume processor t ime

❖ Starvation is possible

I :;}
J-
As the selection of the process who will enter crit ical section is arbitrary.
I_,.';
It may happen that some processes cou ld indefinitely be denied access
❖ Deadlock is possible - consider this scenario on a single-CPU system
""- Process Pl executes the special instruction and enters its CS
'--- Pl is then interrupted to give the CPU to P2, which has higher priority
- - . Now if P2 attempts to use the same resource as Pl, it will be denied due
to the ME mechanism. Thus, it will go into a busy waiting loop
....._ However1 Pl will never be dispatched because it is of lower priority than
another ready process, P2

'-V
Operating Systems - Dr. Abdu lbaset Gaddah 24

24

Operating Systems - Dr. Abdulbaset Gaddah 12


Semaphores.
'
❖ The hardware-based solutions are complicated for application
programmers to use
❖ Semaphore S - a simple synchronization tool
■ Is an integer variable
■ Is accessed only through two standard atomic operations: wait(S) and
signal(S) -
■ When one process modifies the semaphore S value, no other process can
simultaneously modify the same semaphore value

wait (S) {
signal (S)
whi l e (S <= 0) ; .
s-- ; .... '' ..,. S+--+ ;
'
' -r
------------i_ ~

--J,.., .,,..,.
All the modifications (and testi ng ) to the integer value
of the semaphore must be executed indivisibly r,v
Operating Systems - Dr: Abdulbaset Gaddah 25

25

' Two Types of Semaphores \


❖ Binary semaphore (also known as mutex lock) C C. •0I1J,.
1\
■ ] nteger value can range only between O and 1
■ frovides mutual exclusion (e.g., access to a critical section of code)
■ S is initialized to 1

Process Pi:
do {
wait( S );

cr i t i cal s e c ti on
signal( S );
remainder section
wh i l e (T RUE ) ;

Jonly one process allowed entry at a tim~ l


r
'-V
Operating Systems - Dr. .Abdulbaset Gaddah 26

26

Operating Systems - Dr. Abdulbaset Gaddah 13


Now Two Types of Semap~ores (Cont.~ u,J J t..fo.J 1
f 1 4 1 EM
I ❖ Counting semaphore ~,-, . . -C\..a--4
_4
..r'c: ~
III -
•L ... T"

■ Integer value can range over an unrestricted domain -


If ■ Used to aUocate resources with many units avai lable
fesoutees ■ Alllows processes to enter as l ong as more units are availablle
ID ■ ("u""'ev
S is initialized to N (number of units available) number 6f'
of tt"~c:.eto
ecou~,s rse11!.S")
s
■ When a process wishes to use a resource1 it performs wait ( s)
operation (thereby decrementing S by 1)
■ When a process releases a resource, it performs signal (S) operation
(thereby incrementing S by 1)
■ When S value goes to 0, alll resources are being used; processes that
wish to use a resource will be blocked until S becomes greater than 0

Operati ng Systems - Dr: Abdulbaset Gaddah 27

27

Semaphores Usage
"
'-. /

❖ Semaplnores can be used to solve synchronization problems


■ We have 2 concurrently running processes: Pl with a statement S1 and
P2 with a statement S2
■ We reguire that 52 be executed onl:i:: after 51 has comeleted

,,
A common semaphore synch, init ialized to 0

~
I
-
Process Pl: Process P2:

wa i t (s ync h) ; \
'
S1 ;

signal( synch) ; S2;


. P2 will execute 52 only after Pl has invoked s i g n a l (s y n c )
- (
'- V
Operati ng Systems - Dr. .Abdulbaset Gaddah 28

2a •ts,'•
S 1n<'}..,''
15211
~rs,.,
525s,,5
5,5 5ji..,
2 ·- _
Operating Systems - Dr. Abdulbaset Gaddah 14
Pitfall: Semaphores Implementation
'
\...,/

❖ The main disadvantage of the semaphore definition is that it requires


busy waiting_ \
loA ot.r
p
■ Also called a spinlock; because the process spins while waiting for the lock
■ A waiting process must loop continuously in the entry code
■ Waste CPU cycles that some other process might be able to use
productively
■ However, spinlocks are useful on multiprocessor systems when locks are
expected to be held for short times
• One thread can "spin" on one processor while another thread performs its
critical section on another processor
• We then waste a bit of CPU time, but we save context switch time

Operating Systems - Dr: Abdulbaset Gaddah

29

Blocking in Semaphores
❖ To overcome the need for busy waiting. Each semaphore has an
associated queue of processes
■ When wait(S) is called by a process:
• if 5 was "available" (>0), decrement 5 by 1 and let process continue
• if S was' . < =0 rather · · _place
process into a waiting queue associa
• The CPU scheduler then sellects another process to execute

■ ea t
When signal (S) is called by a process:
• if no processes are waiting into the associated queue, increment S by 1
• if pmcesses are waiting into the associated queue, unblock qne (change its
state from waiting to ready and place it in the ready queue)
• The CPU may or may not let the "signaHng" process continue executing,
depending on the CPU-scheduling algorithm

Operating Systems - Dr. .Abdulbaset Gaddah 30

30

Operating Systems - Dr. Abdulbaset Gaddah 15


An Example of Semaphore Mechanism

®
©~1 ------lffi----~ ~-----~•
Processcir

L IIlIIBkttl;:e{I i'Jllt,1.1 ,-
P } - "R('Jldf
Si>ma.J)l,orf,!
l lcloJB~
flTit'IH!
L 1I I I I ;~ I !ID!BIAJ
Blod,m queue Sew.,phol'e Ready qneae

,© l'.J'(H."t'S!il'.DI'

....-----4[IJ....--------,

0
l'rort'.5~1)1"
L I IB!A)c)
Blodrecl. q11eue
[?TT----+ I I I I
SrnrnplloL·e
J
Rt:idy gnt:Ili'

~ I ©
------.
J
Prnm,or

LIIIIBI I 1.-Jd-..J L ~D

A -<,+ . . .
>•-1 J
fl!(l('kt•Ll 111.K'11.@' Sl'JIJ:.tltlJllll" R t.'lld~· (!1U!'1l'

l l) 8 li1.l~ll)lc
©
and B to ready
t.. t...;;'"~' S•~·· ..,,.~
L 1 1 1 1 1
Bt;,~e~ ~ll<ll<
~ Se10aph01~
set
I
Rt.1~r ~am queueHere processes wA, B,-..{and-1:.. C depend
IBIA) c~r»1:,v,

on a result from process D

Operating Systems - Dr. Abdu lbaset Gaddah

31

Semaphore's Structure
"
'-. /
- - - - -- - -
❖ Hence, a semaphore is defined as a "C" structure:

typedef struct {
int va lue ;
struct process *list;
} semaphore S;

❖ With each semaphore there is a11 associated waiting queue


❖ Each entry in a waiting queue has two data items:
■ value (of type integer)
■ pointer to next record in the list
❖ When a process must wait on a semaphore S, it is added to the list
of processes

Operating Systems - Dr. .Abdulbaset Gaddah

32

Operating Systems - Dr. Abdulbaset Gaddah 16


Semaphore's Operations (atomic)
❖ The wait () semaphore operation:
wait(sernaphore *S) {
S- >value --;
if {S- >va lue < 0)
add this process to S- >lis t ;
b lock {);
Suspends the process that invokes it (places
process on the appropriate waiting queue)

❖ The signal() semaphore operation:


Its magnitude is the number
of waiting process
S- >value++;
if {S->value <= 0) { The list can use a fair
remove a process P from S- >list ; policy like , FIFO
wakeup(P) ;
Resumes the execution of a blocked
process P (places P in the ready queue)

Operating Systems - Dr. Abdulbaset Gaddah 33

33

Strong and Weak Semaphores


'
❖ For both counting and binary semaphores, a waiting queue is used
to hold processes waiting on the semaphore

❖ Strong Sema phores


■ The process that has been blocked the longest is released from the
wa jtjng queue first (FIFO)
■ Does not allow for individual starvation

❖ Weak Semaphores ~ I,. ZfO J


■ The order in which processes are removed from the waiting queue is not
specified
■ Does not offer any guarantees with respect to individual starvation

,v
Operating Systems - Dr. Abdulbaset Gaddah 34

34

Operating Systems - Dr. Abdulbaset Gaddah 17


Deadlock and Starvation
❖ Deadlock - two or more processes are waiting indefinitely for an
event that can be caused by only one of the wa iting processes
■ Let S and Q be two semaphores initialized to 1
Po P, 0
o._
wait (S); wait (Q);
wait (S);
=
C c7i
~
wait (Q); ::, ell
_ c
"ai .QI
== 1/)
signal (S); signal (Q); 1ii
::,-
~
signal {Q); signal (S); EB
....a.. ~
Q)
As these signal() operations cannot be
executed, PO and P1 are deadlocked

❖ Starvation - indefinite blocking. A process may never be removed


from the semaphore queue in which it is suspended
■ May occur with a semaphore in LIFO (last-in, first-out) order
~ ~ " "~
Tea
Operating Systems - Dr: Abdu lbaset Gaddah
---------------..+--,-
35

35

Classical Problems of Synchronization


'
❖ Classical problems used to test newly-proposed synchronization
schemes will be presented:
■ The Producer/Consumer Problem
• Using Unbounded-Buffer
• Using Bounded-Buffer

■ The Dining-Philosophers Problem

❖ Semaphores will be used as a solution tool for synchronizati·on

'-V
Operating Systems - Dr. .Abdulbaset Gaddah 36

36

Operating Systems - Dr. Abdulbaset Gaddah 18


, The Producer/Consumer Problem L"f'if'q-1,-, s~,\"e~
~/ ~

❖ A producer process is generating data and placing these in a bulk[ ' e S e>Ut"c:
c~
❖ A consumer process is taking items out of the buffer one at time
❖ We need a buffer to hold items that are produced and eventually
consumed
-
❖ Only one producer or consumer may access the buffer at any one
time
❖ A common paradigm for cooperating processes

❖ The Problem::
........__ ensure that the producer can't add data into full buffer and consumer
can't remove data from an empty buffer

r
Operating Systems - Dr: Abdulbaset Gaddah

37

P/C: Unbounded Buffer


❖ We assume first an unbounded buffer consisting of a linear array of
elements
in points to the next item to be produced
•--~•·out points to the next item to be consumed

0 1 2 3 4

I I I
b[l] b[2] b[3] 1I~[4] I I. . .
b[5]

r
out
r
in

Shaded area indicates portion of buffer that is ccupied

Operating Systems - Dr. Abdulbaset Gaddah 38

38

Operating Systems - Dr. Abdulbaset Gaddah 19


P/C: Unbounded Buffer
'
'-- ,/
.!\,\
bin. . ~'r'b)
ary
❖ We need a semaphore S to perform mutual exclusi·on on the buffer:
only one process at a time can access the buffer
❖ We need another sema12hore N to S:inchronize the 12roducer and
consumer on tile number N ( = in - out) of items in the buffer <c.oul\+r"'
■ An item can be consumed only after it has been created
- -r.,;. The producer is free to add an item into the buffer at any time: itsem
maphore
.....,
c~ounting

performs wait(S) before appending and signal(S) afterwards to


prevent consumer access
❖ It also eerforms signal(N) after each aeeend to increment N
❖ The consumer must first do wait(N) to see if there is an item to
consume ana use wa1ttSJ ana s1gnal(S1 Ea access Ifie 6uffer

(
,v
Operating Systems - Dr. Abdu lbaset Gaddah 39

39

L-

Solution of P/C: Unbounded Buffer


'
'-- , /
Initialization : 'Must perform wait(N) before wait(S),
Semaphore S = 1, N = O; otherwise deadlock occurs if consumer
int in = out = D; enter CS while the buffer is empty
I
do { Producet do ( / Consumer
produce (v); wait{N);
wait(S); wait lS);
append {vJ ; w = take{) ;
signal{SJ; signal{S);
signal {NJ ; consume /wl ;
) while ( TRU E ) ; } while ( TRUE ) ;

append(v): take():
b[in] - v; w ~ b [out] ;
in++ ; out++ ;
return w;
- (
'- V
Operating Systems - Dr; .Abdu lbaset Gaddah 40

40

Operating Systems - Dr. Abdulbaset Gaddah 20


P/C: Bound Circular Buffer of Size k
❖ We need a semaphore S to have mutual exclusion on buffer access C ,_
bin ary
-'4' t':,:,
❖ We need a semaphore N to synchronize producer and consumer on t:. c u tt :,)
the number of consumable items co
oun
n11tin.,g
❖ We need a semaphore E to synchronize producer and consumer on
the number of empty spaces co
ounting
b[I] b[21 b[)J b[41 bf5] • • • • El
(a)

blll b[2] b[J ) b[4] b.[5) • • • • El


l
In 0111
Consumes only when number N (bJ Produces only when number E
of items is at least 1 of empty spaces is at least 1

Operating Systems - Dr. Abdulbaset Gaddah 41

41

Solution of P/C: Bound Circular Buffer of Size k


" ·· r · ~"~•t ~ llee ss-P-\ctt.s
",/1nit1a 1zat1on: paces
Semaphore S = 1, N = 0, E =~
int in = out = O;

do { Producet do l Consumer
produce (v); wait{N) ;
wait (El; wait(S) ;
wait{S); w = tak e O ;
append {vl ; signal{S) ;
signal{S) ; signal (E) ;
signal {N) ; consume {w) ;
) while [ TRUE ) ; l while (TRUE);

append(v): take():
b[ i n ] - v; w ~ b [out] ;
in= (in+l) mod k; out= {out+l) mod k ;
return w;
(
'- V
Operating Systems - Dr. .Abdulbaset Gaddah 42

42

Operating Systems - Dr. Abdulbaset Gaddah 21


The Dining Philosophers Problem
❖ Five philosophers spend their time thinking
and eating
cite
e sou
urc
ces
❖ The table is laid with five single chopsticks
❖ When a philosopher wants to eat, he picks up
two chopsticks - one from his left and one
from his right
■ Only one chopstick can be picked up at a time
■ Clearly, a philosopher can't pick up a chopstick
that is already in the hand of a neighbor
❖ When a philosopher wants to think, he puts
back both chopsticks at their original place
❖ Presents tne difficulty of allocating multiple
resources to multiple processes without
deadlock and starvation
Operating Systems - Dr. Abdulbaset Gaddah 43

43

The Dining Philosophers Problem


"
❖ Each philosopher is a process
❖ One semaphore per chopstick :
■ semapho r e chops tick [ 5 ] ; All initialized to 1
❖ A first attempt:
■ Although this solution guarantees that no two neighbors are eating
simultaneously, it nevertheless could create a deadlock
■ Suppose that all five philosophers become hungry simultaneously and
each one grabs his left chopstick!
do { Process Pl
// think
wait(chop stick [ i]);
wait(chop st ic k [ li +l) % 5]);
// eat
signal(chopstick[ i ]);
signal(chopstick[(i+l) % 5 ] );
} while (TRUE);

Operating Systems - Dr. .Abdulbaset Gaddah

44

Operating Systems - Dr. Abdulbaset Gaddah 22


The Dining Philosophers Problem
❖ A possible solution:
■ At most four philosophers to be sitting simultaneously at the table
• Hence, we can use another semaphore T with initial value of 4 that woulld limit
the number of philosophers "sitting at the table"
■ Then one philosopher can always eat when the other three are holding
one chopstick

do { Process Pi
// think
wait (T) ;
wait(chopstick[i ] );
wait (chopstick[( i +l) % 5]) ;
// eat
signal(chopstick [ i]);
signa l (chopstick [ (i+l) % 5 ]);
sign a l (T) ;
wh i l e (TRUE) ;

Operating Systems - Dr. Abdulbaset Gaddah 45

45

Problems with Semaphores


",.
'- ,/
~ - - - - - -- - -

❖ Semaphores provide a powerful tool for enforcing mutual exclusion


and coordinate processes

❖ But wait(S) and siqnal(S) are scattered among several processes.


Hence, difficult to understand their effects

......, ""St Usage must be correct in all the processes ( correct order, correct
variables, no omissions)

'-.:. One bad (or malicious) process can fail the entire collection of
processes

'-1--'
Operating Systems - Dr. Abdulbaset Gaddah 46

46

Operating Systems - Dr. Abdulbaset Gaddah 23


P
A
Exercises
❖ .A system is having 3 processes each requires 2 units of resource R to
complete its task. What is the minimum number of units of R required
so that no deadlock will occur? 4
4
❖ A system is having 3 user processes Pl, P2 and P3 where Pl requires
3 units of resource R, P2 requires 4 units of resource R, P3 requires 5
units of resource R. What is the minimum number of units of R that
ensures no deadlock wil l occur?

❖ If there are 8 units of resource R in the system and each process in


the system requires 3 units of resource R, then how many processes
can be present at maximum so that no deadlock will occur?

❖ .A counting semaphore S is initialized to 7. Then 1 20 wait(S)


operations and 15 signal(S) operations were performed on S. What is
the final1value of semaphore S?

Operating Systems - Dr: Abdulbaset Gaddah 47

47

Chapter 6: Processes Synchronization

THANK YOU

Questi,ons & comments


Operating Systems - Dr. Abdulbaset Gaddah 48

48

Operating Systems - Dr. Abdulbaset Gaddah 24

You might also like