chapter 6 semaphores

36
1 Chapter 6 Chapter 6 Semaphores Semaphores

Upload: jalila

Post on 12-Jan-2016

95 views

Category:

Documents


2 download

DESCRIPTION

Chapter 6 Semaphores. Semaphores. Major advance incorporated into many modern operating systems (Unix, OS/2) A semaphore is a non-negative integer that has two indivisible, valid operations. Semaphore Operations. Wait(s) (Dijkstra – P(s) – Proberen (to test) If s > 0 then s:= s - 1 - PowerPoint PPT Presentation

TRANSCRIPT

Page 1: Chapter 6 Semaphores

1

Chapter 6Chapter 6

SemaphoresSemaphores

Page 2: Chapter 6 Semaphores

2

SemaphoresSemaphores

Major advance incorporated into many Major advance incorporated into many modern operating systems (Unix, OS/2)modern operating systems (Unix, OS/2)

A semaphore isA semaphore is a non-negative integera non-negative integer that has two indivisible, valid operationsthat has two indivisible, valid operations

Page 3: Chapter 6 Semaphores

3

Semaphore OperationsSemaphore Operations

Wait(s)Wait(s) (Dijkstra – P(s) – Proberen (to test)(Dijkstra – P(s) – Proberen (to test)If s > 0 If s > 0 then s:= s - 1then s:= s - 1

else else block this processblock this process

Signal(s)Signal(s) (Dijkstra – V(s) – Verhogen (to (Dijkstra – V(s) – Verhogen (to increment)increment)

If If there is a blocked process on this there is a blocked process on this semaphoresemaphore

then then wake it upwake it up

else s:= s + 1else s:= s + 1

Page 4: Chapter 6 Semaphores

4

More on SemaphoresMore on Semaphores

The other valid operation is initialisationThe other valid operation is initialisation Two types of semaphoresTwo types of semaphores

binary semaphores can only be 0 or 1binary semaphores can only be 0 or 1 counting semaphores can be any non-counting semaphores can be any non-

negative integernegative integer Semaphores are an OS service Semaphores are an OS service

implemented using one of the methods implemented using one of the methods shown alreadyshown already usually by disabling interrupts for a very usually by disabling interrupts for a very

short timeshort time

Page 5: Chapter 6 Semaphores

5

The Critical Section Problem for Two The Critical Section Problem for Two ProcessesProcesses

Note : S ← (1,Note : S ← (1,øø) means semaphore S has a value of 1 and the set of blocked processes is null) means semaphore S has a value of 1 and the set of blocked processes is null

Page 6: Chapter 6 Semaphores

6

State DiagramState Diagram

Mutual exclusion : Try to find a state (p2, q2) in which both processes are in their Mutual exclusion : Try to find a state (p2, q2) in which both processes are in their CS. Since there is no such state, mutual exclusion property holdsCS. Since there is no such state, mutual exclusion property holds

No Deadlock : No states in which both processes are blockedNo Deadlock : No states in which both processes are blocked No Starvation : If a process executes its wait statement, the next state is either CS No Starvation : If a process executes its wait statement, the next state is either CS

or blocked. When blocked the only way is to a state in which the blocked process or blocked. When blocked the only way is to a state in which the blocked process continues with a signal statementcontinues with a signal statement

Page 7: Chapter 6 Semaphores

7

The Critical Section Problem for The Critical Section Problem for NN ProcessesProcesses

Mutual exclusion and freedom from deadlock are still Mutual exclusion and freedom from deadlock are still hold but there may be hold but there may be starvationstarvation

Page 8: Chapter 6 Semaphores

8

Scenario for Starvation (3 Scenario for Starvation (3 Processes)Processes)

Processes Processes pp and and rr conspire to starve conspire to starve process process qq (see lines 3 and 7) (see lines 3 and 7)

Page 9: Chapter 6 Semaphores

9

Order Of Execution Order Of Execution ProblemsProblems

This mergesort algorithm uses two independent sort This mergesort algorithm uses two independent sort processes (may be more) and a merge process to processes (may be more) and a merge process to merge the first and second halves when sorting is overmerge the first and second halves when sorting is over

The correct synchronization is achived by two binary The correct synchronization is achived by two binary semaphores as shown abovesemaphores as shown above

Page 10: Chapter 6 Semaphores

10

Producer - Consumer Producer - Consumer with a with a SingleSingle Buffer Buffer

Program producerconsumer;Program producerconsumer;Var s: semaphore;Var s: semaphore;Procedure producer;Procedure producer;beginbegin

repeat repeat produce;produce;wait(s);wait(s);putinbuffer; putinbuffer; signal(s); signal(s);

until false;until false;End;End;Procedure consumer;Procedure consumer;BeginBegin

repeatrepeatwait(s);wait(s);getfrombuffer; getfrombuffer; signal(s); signal(s); consume;consume;

until false;until false;End;End;Begin (* main program *)Begin (* main program *)

s:= 1;s:= 1;cobegin producer; consumer coend;cobegin producer; consumer coend;

End.End.

Page 11: Chapter 6 Semaphores

11

Producer - Consumer Producer - Consumer with with InfiniteInfinite Number of BuffersNumber of Buffers

Program producerconsumer;Program producerconsumer;Var Var s: semaphore;s: semaphore; (* for mutual exclusion on access to buffer *) (* for mutual exclusion on access to buffer *)

n: semaphore;n: semaphore; (* to control empty and full buffer conditions *)(* to control empty and full buffer conditions *)Procedure producer;Procedure producer;beginbegin

repeat repeat produce;produce;wait(s); wait(s); putinbuffer; putinbuffer; signal(s); signal(s); signal(n);signal(n); (* send a full buffer ready signal *)(* send a full buffer ready signal *)

until false;until false;End;End;Procedure consumer;Procedure consumer;BeginBegin

repeatrepeatwait(n);wait(n); (* wait for a full buffer *)(* wait for a full buffer *)wait(s); wait(s); getfrombuffer; getfrombuffer; signal(s); signal(s); consume;consume;

until false;until false;End;End;Begin (* main program *)Begin (* main program *)

s:= 1; s:= 1; n:= 0;n:= 0;cobegin producer; consumer coend;cobegin producer; consumer coend;

End.End.

Page 12: Chapter 6 Semaphores

12

Producer - Consumer Producer - Consumer with with InfiniteInfinite Number of Buffers (modification 1)Number of Buffers (modification 1)

Program producerconsumer;Program producerconsumer;Var Var s: semaphore;s: semaphore;

n: semaphore;n: semaphore;Procedure producer;Procedure producer;beginbegin

repeat repeat produce;produce;wait(s);wait(s); putinbuffer; putinbuffer; signal(n);signal(n); signal(s);signal(s);

until false;until false;End;End;Procedure consumer;Procedure consumer;BeginBegin

repeatrepeatwait(n);wait(n);wait(s);wait(s); getfrombuffer; getfrombuffer; signal(s); signal(s); consume;consume;

until false;until false;End;End;Begin (* main program *)Begin (* main program *)

s:= 1; n:= 0;s:= 1; n:= 0;cobegin producer; consumer coend;cobegin producer; consumer coend;

End.End.

signal(s); signal(n); in producer is changed to signal(n); signal(s);

Any change in solution?

No change since producer can not be blocked in CS but CS is a bit long now.

Page 13: Chapter 6 Semaphores

13

Producer - Consumer Producer - Consumer with with InfiniteInfinite Number of Buffers (modification 2)Number of Buffers (modification 2)

Program producerconsumer;Program producerconsumer;Var Var s: semaphore;s: semaphore;

n: semaphore;n: semaphore;Procedure producer;Procedure producer;beginbegin

repeat repeat produce;produce;

wait(s);wait(s); putinbuffer; putinbuffer; signal(s); signal(s); signal(n); signal(n);

until false;until false;End;End;Procedure consumer;Procedure consumer;BeginBegin

repeatrepeatwait(s); wait(n);wait(s); wait(n); getfrombuffer; getfrombuffer; signal(s); signal(s);

consume;consume; until false; until false;

End;End;Begin (* main program *)Begin (* main program *)

s:= 1; n:= 0;s:= 1; n:= 0;cobegin producer; consumer coend;cobegin producer; consumer coend;

EndEnd..

wait(n); wait(s); in consumer is changed to wait(s); wait(n);

Any change in solution?

Suppose consumer enters CS with n = 0. It will be blocked on wait(n). Producer can not also enter CS. So, the system is DEADLOCKED!

Page 14: Chapter 6 Semaphores

14

Producer - Consumer Producer - Consumer with with FiniteFinite Number Number of Buffersof Buffers

Program producerconsumer;Program producerconsumer;Var Var s: semaphore;s: semaphore;

full, empty: semaphore;full, empty: semaphore;Procedure producer;Procedure producer;beginbegin

repeat repeat produce;produce;wait(emtpy);wait(emtpy);wait(s);wait(s); putinbuffer; putinbuffer; signal(s); signal(s); signal(full);signal(full);

until false;until false;End;End;Procedure consumer;Procedure consumer;BeginBegin

repeatrepeatwait(full);wait(full);wait(s);wait(s); getfrombuffer; getfrombuffer; signal(s); signal(s); signal(empty);signal(empty);consume;consume;

until false;until false;End;End;Begin (* main program *)Begin (* main program *)

s:= 1; s:= 1; full:= 0; empty:= 10; (* 10 empty buffers initially *)full:= 0; empty:= 10; (* 10 empty buffers initially *)cobegin producer; consumer coend;cobegin producer; consumer coend;

End.End.

Page 15: Chapter 6 Semaphores

15

Dining PhilosophersDining Philosophers

5 seating places, 5 plates of spagetti and 5 forks5 seating places, 5 plates of spagetti and 5 forks A philosophers life cycleA philosophers life cycle

Repeat think; eat foreverRepeat think; eat forever Eating can only be done with 2 forksEating can only be done with 2 forks Devise a ritual (protocol) that will allow the philosophers to eat. Devise a ritual (protocol) that will allow the philosophers to eat.

The protocol should satisfy The protocol should satisfy mutual exclusionmutual exclusion (no two (no two philosophers try to use the same fork simultaneously) , philosophers try to use the same fork simultaneously) , free from free from deadlockdeadlock and and absense of starvation absense of starvation

Figure is from Modern OS by Tanenbaum

Page 16: Chapter 6 Semaphores

16

Dining Philosophers Solution – First AttemptDining Philosophers Solution – First Attempt

Program diningphilosophers;Program diningphilosophers;VarVar i i : integer;: integer;

fork fork : array[0..4] of semaphore;: array[0..4] of semaphore;

Procedure philosopher (i : integer);Procedure philosopher (i : integer);BeginBegin

repeatrepeatthink;think;wait(fork[i]); wait(fork[i]); (* get left fork *)(* get left fork *)wait(fork[(i+1) mod 5];wait(fork[(i+1) mod 5]; (* get right fork *)(* get right fork *)eat;eat;signal(fork[i]);signal(fork[i]); (* return left fork *)(* return left fork *)signal(fork[(i+1) mod 5];signal(fork[(i+1) mod 5]; (* return right fork *)(* return right fork *)

until false;until false;End;End;Begin (* main *)Begin (* main *)

for i:= 0 to 4 do fork[i]:= 1; (* initially all forks are available *)for i:= 0 to 4 do fork[i]:= 1; (* initially all forks are available *)cobegin cobegin

philosopher(0); philosopher(1); philosopher(2); philosopher(0); philosopher(1); philosopher(2); philosopher(3); philosopher(4);philosopher(3); philosopher(4);coend;coend;

End.End.

Page 17: Chapter 6 Semaphores

17

Comments on First AttemptComments on First Attempt Mutual exclusion is implemented by a binary Mutual exclusion is implemented by a binary

semaphore semaphore forkfork Deadlock is possible if all 5 philosophers take Deadlock is possible if all 5 philosophers take

the left forks simultaneously then all would wait the left forks simultaneously then all would wait for the right forkfor the right fork

How to handle the deadlock and ensure How to handle the deadlock and ensure liveliness?liveliness? Let at the most 4 philosophers to sit and eat. Let at the most 4 philosophers to sit and eat. Two of them can eat, one holds a fork and the other Two of them can eat, one holds a fork and the other

just sitsjust sits One philosopher can eat and the other 3 can hold One philosopher can eat and the other 3 can hold

their left forkstheir left forks

Page 18: Chapter 6 Semaphores

18

Correct SolutionCorrect SolutionProgram diningphilosophers;Program diningphilosophers;Var fork : array[0..4] of semaphore;Var fork : array[0..4] of semaphore;

i : integer;i : integer; table : semaphore; (* seating limit *)table : semaphore; (* seating limit *)

Procedure philosopher (i : integer);Procedure philosopher (i : integer);BeginBegin

repeatrepeatthink;think;wait(table);wait(table);wait(fork[i]); wait(fork[i]); (* get left fork *)(* get left fork *)wait(fork[(i+1) mod 5];wait(fork[(i+1) mod 5]; (* get right fork *)(* get right fork *)eat;eat;signal(fork[i]);signal(fork[i]); (* return left fork *)(* return left fork *)signal(fork[(i+1) mod 5];signal(fork[(i+1) mod 5]; (* return right fork *)(* return right fork *)signal(table);signal(table);

until false;until false;End;End;Begin (* main *)Begin (* main *)

for i:= 0 to 4 do fork[i]:= 1; for i:= 0 to 4 do fork[i]:= 1; table:= 4;table:= 4;cobegin cobegin

philosopher(0); philosopher(1); philosopher(2); philosopher(0); philosopher(1); philosopher(2); philosopher(3); philosopher(4);philosopher(3); philosopher(4);coend;coend;

End.End.

Page 19: Chapter 6 Semaphores

19

Barz’s Simulation of General Barz’s Simulation of General SemaphoresSemaphores

KK is the initial value of semaphore is the initial value of semaphore Semaphore Semaphore gategate is used to block and unblock processes is used to block and unblock processes Variable Variable countcount holds the value of semaphore simulatedholds the value of semaphore simulated Semaphore Semaphore SS is used as a mutex when accessing the count is used as a mutex when accessing the count

variablevariable

Page 20: Chapter 6 Semaphores

20

Simulated WaitSimulated Wait

The first process to execute a simulated wait will The first process to execute a simulated wait will pass through p1 since gate is initialized to 1, but pass through p1 since gate is initialized to 1, but others will be blockedothers will be blocked

The first process and each subsequent process The first process and each subsequent process (up to a total of k-1) will execute p5 so that other (up to a total of k-1) will execute p5 so that other processes will pass through the gateprocesses will pass through the gate

The k’th process will be blocked (count is now 0) The k’th process will be blocked (count is now 0) at p1at p1

Page 21: Chapter 6 Semaphores

21

CoursewareCourseware We will use the concurrent Pascal interpreter of Ben-Ari to We will use the concurrent Pascal interpreter of Ben-Ari to

solve our concurrent programs using semaphores.solve our concurrent programs using semaphores. A new data type “semaphore” is available to declare A new data type “semaphore” is available to declare

semaphores. The initial value of a semaphore can be set in semaphores. The initial value of a semaphore can be set in the main program section using an assignment (original the main program section using an assignment (original concurent Pascal) or by an initialsem (BACI, jBACI) concurent Pascal) or by an initialsem (BACI, jBACI) statement. Apart from this, you can only use semaphores in statement. Apart from this, you can only use semaphores in “wait”“wait” and and “signal”“signal” primitives. You should not inspect or try primitives. You should not inspect or try to assign a value for a semaphore in the program.to assign a value for a semaphore in the program.

The interpreter has a new construct The interpreter has a new construct ““cobegin ... coend”cobegin ... coend”

to start concurrent processes in the main section of your to start concurrent processes in the main section of your programprogram

The The concurrent Pascal interpreterconcurrent Pascal interpreter has two versions. has two versions. Unfortunately both versions have slight differencesUnfortunately both versions have slight differences

Page 22: Chapter 6 Semaphores

22

Ben-Ari’s OriginalBen-Ari’s Original

Ben-Ari’s original is in the appendix of the Ben-Ari’s original is in the appendix of the book “book “Concurrent Programming By M. Ben-Concurrent Programming By M. Ben-Ari”Ari”

I have modified this SW so that it can I have modified this SW so that it can accomodate more concurrent processes and accomodate more concurrent processes and a “for” loop can be used within the a “for” loop can be used within the “cobegin..coend” block (which is not “cobegin..coend” block (which is not compatible with the version described on the compatible with the version described on the next slide). next slide).

You can find this version (source and You can find this version (source and executable) in my public directoryexecutable) in my public directory

Page 23: Chapter 6 Semaphores

23

BACI and jBACIBACI and jBACI BACI stands for Ben-Ari’s Concurrent InterpreterBACI stands for Ben-Ari’s Concurrent Interpreter

BACI url: BACI url: http://www.mines.edu/fs_home/tcamp/baci/ This software is available for Windows and Unix This software is available for Windows and Unix

environments in C and Pascal.environments in C and Pascal. The other version jBACI is maintained by Ben-Ari himselfThe other version jBACI is maintained by Ben-Ari himself

jBACI url: jBACI url: http://stwww.weizmann.ac.il/g-cs/benari/jbaci/

I will use jBACI Windows and Pascal versions (You I will use jBACI Windows and Pascal versions (You should do the same for this course). should do the same for this course).

To use jBACI you should install and run the Sun java To use jBACI you should install and run the Sun java runtime environment which is available at runtime environment which is available at http://java.sun.com/j2se/1.4.2/download.html

Page 24: Chapter 6 Semaphores

24

Example 1 - TunnelExample 1 - TunnelA computer system is being used to control the flow of trafficA computer system is being used to control the flow of traffic through a roadthrough a road tunnel. For safety reasons, there must never be moretunnel. For safety reasons, there must never be more than approximately N vehicles in the tunnel at one time. Trafficthan approximately N vehicles in the tunnel at one time. Traffic lights at the entrance control the entry of traffic and vehiclelights at the entrance control the entry of traffic and vehicle detectors at entrance and exit are used to measure the traffic flow.detectors at entrance and exit are used to measure the traffic flow.

An entrance process records all vehicles entering the tunnel,An entrance process records all vehicles entering the tunnel, and a and a

separate exit process records all vehicles leaving. Each ofseparate exit process records all vehicles leaving. Each of these these processes can, at any time, read its vehicle detector toprocesses can, at any time, read its vehicle detector to determine determine how many vehicles have passed since the last reading washow many vehicles have passed since the last reading was made. A made. A traffic lights process controls the traffic lights at thetraffic lights process controls the traffic lights at the entrance to entrance to the tunnel which the tunnel which is is set to red whenever the number ofset to red whenever the number of vehicles in vehicles in the tunnel equals or exceeds N, and green otherwise.the tunnel equals or exceeds N, and green otherwise.

Page 25: Chapter 6 Semaphores

25

Tunnel ProgramTunnel Programprogram tunnel;program tunnel;

const const limit = 5;limit = 5;Var Var no_vehicles no_vehicles : integer; : integer; {in tunnel}{in tunnel} red red : boolean; : boolean; {traffic light}{traffic light} screen screen : semaphore; : semaphore; {controls {controls

screen display screen}screen display screen} i i : integer;: integer; max max : integer;: integer;

procedure entrance; .......... end;procedure entrance; .......... end;procedure exit; ................... end;procedure exit; ................... end;procedure lights; ............... end;procedure lights; ............... end;

begin {main}begin {main} no_vehicles := 0; max:= limit*2; red:= false; initialsem(screen,1);no_vehicles := 0; max:= limit*2; red:= false; initialsem(screen,1); cobegin lights; entrance; exit coend;cobegin lights; entrance; exit coend;end.end.

Page 26: Chapter 6 Semaphores

26

Procedure Procedure EntranceEntranceprocedure entrance;procedure entrance;var entry_counter :integer;var entry_counter :integer;beginbegin while true dowhile true do

beginbeginif not red then beginif not red then begin

entry_counter:= random(max); entry_counter:= random(max); no_vehicles:= no_vehicles + no_vehicles:= no_vehicles +

entry_counter;entry_counter; wait(screen);wait(screen); write(' Entry reading .. ',entry_counter);write(' Entry reading .. ',entry_counter);

endendelse beginelse begin

wait(screen);wait(screen); write(' Light is now RED ... ');write(' Light is now RED ... ');

end;end; writeln(' No of vehicles in tunnel .. ',no_vehicles);writeln(' No of vehicles in tunnel .. ',no_vehicles); signal(screen);signal(screen);

end;end;end;end;

Page 27: Chapter 6 Semaphores

27

Procedure Procedure ExitExit

procedure exit;procedure exit;var exit_counter :integer;var exit_counter :integer;beginbegin while true dowhile true do

beginbegin exit_counter:= random(no_vehicles);exit_counter:= random(no_vehicles); no_vehicles:= no_vehicles - exit_counter;no_vehicles:= no_vehicles - exit_counter; wait(screen);wait(screen); writeln(' Vehicles passed .. ',exit_counter,writeln(' Vehicles passed .. ',exit_counter, ' No of vehicles in tunnel .. ' No of vehicles in tunnel ..

',no_vehicles);',no_vehicles); signal(screen);signal(screen); end;end;end;end;

Page 28: Chapter 6 Semaphores

28

Procedure Procedure LightsLights

procedure lights;procedure lights;beginbegin while true dowhile true do

beginbegin if no_vehicles >= limit then red:= true else if no_vehicles >= limit then red:= true else

red:= false;red:= false; wait(screen);wait(screen); write(' Traffic light is .. '); write(' Traffic light is .. '); if red then writeln('RED') else if red then writeln('RED') else

writeln('GREEN');writeln('GREEN'); signal(screen);signal(screen); end; end; end;end;

Page 29: Chapter 6 Semaphores

29

Example 2 – The Bear and Example 2 – The Bear and The BeesThe Bees

There are There are n n honeybees and a hungry bearhoneybees and a hungry bear which which share a pot of honey.share a pot of honey.The pot is initially empty; its capacity is The pot is initially empty; its capacity is HH portions of honey. portions of honey. The bear sleeps until the pot is full,The bear sleeps until the pot is full, then eats then eats all the honey and goes back to sleep. all the honey and goes back to sleep. Each bee repeatedly gathers one portion of Each bee repeatedly gathers one portion of honey and puts it in the pot; the bee who fills honey and puts it in the pot; the bee who fills the pot the pot wakes up wakes up the bear. the bear.

Page 30: Chapter 6 Semaphores

30

Bear and Bees ProgramBear and Bees Program

Program bear_and_bees;Program bear_and_bees;const n = 3; const n = 3; {three bees}{three bees} h = 7; h = 7; {portions for pot}{portions for pot}var i var i : integer;: integer; pot pot : integer;: integer; screen screen : semaphore:=1;: semaphore:=1; potmutex potmutex : semaphore:=1; (* access to pot is : semaphore:=1; (* access to pot is

mutually exclusive *)mutually exclusive *) bear_wakeup bear_wakeup : semaphore:=0; (* bear is sleeping *): semaphore:=0; (* bear is sleeping *) bee_fill_pot bee_fill_pot : semaphore:=h;: semaphore:=h;

procedure eat; var i : integer; begin for i:= 1 to random(50) do end;procedure eat; var i : integer; begin for i:= 1 to random(50) do end;procedure gather_honey; var i : integer; begin for i:= 1 to random(15) procedure gather_honey; var i : integer; begin for i:= 1 to random(15)

do end;do end;

procedure bee(i:integer); .............. end;procedure bee(i:integer); .............. end;procedure bear; ............................. end;procedure bear; ............................. end;

begin {main}begin {main} pot:= 0; pot:= 0; cobegin bee(1); bee(2); bee(3); bear coend;cobegin bee(1); bee(2); bee(3); bear coend;end.end.

Page 31: Chapter 6 Semaphores

31

Procedure Procedure BeeBeeprocedure bee(i:integer);procedure bee(i:integer);beginbegin repeatrepeat wait(bee_fill_pot); (* wait for a signal to start filling when bear wait(bee_fill_pot); (* wait for a signal to start filling when bear

finishes the pot *)finishes the pot *) wait(screen); writeln('bee : ',i,' is gathering honey '); wait(screen); writeln('bee : ',i,' is gathering honey ');

signal(screen); signal(screen); gather_honey;gather_honey; wait(potmutex); if pot < h then pot:=pot+1; (* update pot *)wait(potmutex); if pot < h then pot:=pot+1; (* update pot *) wait(screen); writeln('bee : ',i,' is filling the pot which has wait(screen); writeln('bee : ',i,' is filling the pot which has

',pot,' portions now'); signal(screen); ',pot,' portions now'); signal(screen); if pot = h then begin if pot = h then begin

signal(bear_wakeup); (* wake up bear when pot is full signal(bear_wakeup); (* wake up bear when pot is full *)*)

wait(screen); wait(screen); writeln('bee : ',i,' is waking the bear up .. pot = ',pot);writeln('bee : ',i,' is waking the bear up .. pot = ',pot); signal(screen)signal(screen) end;end; signal(potmutex); (* now other bees can fill the pot *)signal(potmutex); (* now other bees can fill the pot *) until false;until false;end;end;

Page 32: Chapter 6 Semaphores

32

Procedure Procedure BearBearprocedure bear;procedure bear;var j : integer;var j : integer;beginbegin repeatrepeat wait(screen); writeln('bear is now wait(screen); writeln('bear is now

sleeping'); signal(screen);sleeping'); signal(screen); wait(bear_wakeup); (* bear wakes up wait(bear_wakeup); (* bear wakes up

*)*) wait(screen); wait(screen);

writeln('bear is now awake and is eating writeln('bear is now awake and is eating ',pot,' portions'); ',pot,' portions'); signal(screen);signal(screen);

pot:=0; pot:=0; eat; eat;

for j:= 1 to h do signal(bee_fill_pot); for j:= 1 to h do signal(bee_fill_pot); (* signal bees *)(* signal bees *)

until false;until false;end;end;

Page 33: Chapter 6 Semaphores

33

Comments on SolutionComments on Solution

Time taking actions can be simulated using a Time taking actions can be simulated using a loop which executed in a random fashion as in loop which executed in a random fashion as in “eat” and “gather_honey”“eat” and “gather_honey”

A semaphore should be used for each write A semaphore should be used for each write statements so that they are in order. The statements so that they are in order. The interpreter executes the pseudo code of a interpreter executes the pseudo code of a process for a number of instructions and the process for a number of instructions and the switches the process. If the process is switches the process. If the process is interrupted while writing, the output may interrupted while writing, the output may mixed with the output of other processes.mixed with the output of other processes.

Page 34: Chapter 6 Semaphores

34

Example 3 – A Three Way Example 3 – A Three Way RendezvousRendezvous

{ Consider three processes p1, p2, and p3. { Consider three processes p1, p2, and p3. Implement a 3-way rendezvous to synchronize these processes }Implement a 3-way rendezvous to synchronize these processes }

program synchronization;program synchronization;const n = 3;const n = 3;var s : array[1..n] of semaphore; {signal to send and wait at var s : array[1..n] of semaphore; {signal to send and wait at

the rendezvous point }the rendezvous point } screen : semaphore; {for the screen}screen : semaphore; {for the screen} i : integer;i : integer;

procedure p(i :integer); ................... end;procedure p(i :integer); ................... end;

begin {main}begin {main} for i:= 1 to n do initialsem(s[i],0);for i:= 1 to n do initialsem(s[i],0); initialsem(screen,1);initialsem(screen,1); cobegin p(1); p(2); p(3) coend;cobegin p(1); p(2); p(3) coend;end.end.

Page 35: Chapter 6 Semaphores

35

Procedure Procedure PPprocedure p(i :integer);procedure p(i :integer);var j,k,r :integer;var j,k,r :integer;beginbegin while true dowhile true do beginbegin r:= random(100);r:= random(100); wait(screen); writeln('Process ',i,' is executing for ',r,' units'); wait(screen); writeln('Process ',i,' is executing for ',r,' units');

signal(screen);signal(screen); k:=0; for j:= 1 to r do k:= k+ 1; (* let time pass *)k:=0; for j:= 1 to r do k:= k+ 1; (* let time pass *)

wait(screen); writeln('Process ',i,' is waiting for others ..'); wait(screen); writeln('Process ',i,' is waiting for others ..'); signal(screen);signal(screen);

for j:= 1 to n do if j <> i then signal(s[j]); (* send arrival for j:= 1 to n do if j <> i then signal(s[j]); (* send arrival messages *)messages *)

for j:= 1 to n-1 do wait(s[i]); (* wait for reply from each process for j:= 1 to n-1 do wait(s[i]); (* wait for reply from each process *)*)

wait(screen); writeln('Process ',i,' has made the rendezvous ..'); wait(screen); writeln('Process ',i,' has made the rendezvous ..'); signal(screen);signal(screen);

end;end;end;end;

Page 36: Chapter 6 Semaphores

36

Comments on SolutionComments on Solution

When a process When a process pp reaches a rendezvous reaches a rendezvous point it sends messages to the other point it sends messages to the other processes to announce the fact that it processes to announce the fact that it had arrived. After that, it waits had arrived. After that, it waits acknowlegements from the other acknowlegements from the other processes before proceeding.processes before proceeding.