1 chapter 2.3 : interprocess communication process concept process concept process scheduling ...

33
1 Chapter 2.3 : Chapter 2.3 : Interprocess Interprocess Communication Communication Process concept Process concept Process scheduling Process scheduling Interprocess communication Interprocess communication Deadlocks Deadlocks Threads Threads

Upload: esmond-gray

Post on 04-Jan-2016

244 views

Category:

Documents


1 download

TRANSCRIPT

Page 1: 1 Chapter 2.3 : Interprocess Communication Process concept  Process concept  Process scheduling  Process scheduling  Interprocess communication Interprocess

1

Chapter 2.3 : Chapter 2.3 : Interprocess Interprocess

CommunicationCommunication Process concept Process concept Process scheduling Process scheduling Interprocess communicationInterprocess communication DeadlocksDeadlocks ThreadsThreads

Page 2: 1 Chapter 2.3 : Interprocess Communication Process concept  Process concept  Process scheduling  Process scheduling  Interprocess communication Interprocess

2

Producer - Consumer Producer - Consumer ProblemProblem

Buffer is shared (ie., it is a shared variable)Buffer is shared (ie., it is a shared variable)

Producer Process Consumer Process

Produce

Put in buffer Consume

Get from buffer

BUFFER

Page 3: 1 Chapter 2.3 : Interprocess Communication Process concept  Process concept  Process scheduling  Process scheduling  Interprocess communication Interprocess

3

Progress in time…..Progress in time…..

Both processes are started at the same time Both processes are started at the same time and consumer uses some old value initiallyand consumer uses some old value initially

3 instead of 2!

Producer

Consumer1 2 c2

p1 p4p3p2 4321

t

Buffer

c1

Page 4: 1 Chapter 2.3 : Interprocess Communication Process concept  Process concept  Process scheduling  Process scheduling  Interprocess communication Interprocess

4

A Race ConditionA Race Condition

Because of the timing and which Because of the timing and which process starts firstprocess starts first

There is a chance that There is a chance that different different executions may end up with different executions may end up with different resultsresults

Page 5: 1 Chapter 2.3 : Interprocess Communication Process concept  Process concept  Process scheduling  Process scheduling  Interprocess communication Interprocess

5

Critical SectionsCritical Sections Critical SectionCritical Section

A section of code in which the A section of code in which the process accesses and modifies process accesses and modifies shared variablesshared variables

Mutual ExclusionMutual Exclusion A method of preventing for ensuring A method of preventing for ensuring

that one (or a specified number) of that one (or a specified number) of processes are in a critical sectionprocesses are in a critical section

Page 6: 1 Chapter 2.3 : Interprocess Communication Process concept  Process concept  Process scheduling  Process scheduling  Interprocess communication Interprocess

6

Why Processes Need to Why Processes Need to Communicate?Communicate?

To synchronize their executionsTo synchronize their executions

To exchange data and To exchange data and

informationinformation

Page 7: 1 Chapter 2.3 : Interprocess Communication Process concept  Process concept  Process scheduling  Process scheduling  Interprocess communication Interprocess

7

Rules to Form Critical Rules to Form Critical SectionsSections

1. 1. No two processes may be No two processes may be simultaneously inside their CS simultaneously inside their CS (mutual exclusion)(mutual exclusion)

2.2. No assumptions are made about No assumptions are made about relative process speeds or number relative process speeds or number of CPUsof CPUs

3.3. A process outside a CS should not A process outside a CS should not block other processesblock other processes

4.4. No process should wait forever No process should wait forever before entering its CSbefore entering its CS

Page 8: 1 Chapter 2.3 : Interprocess Communication Process concept  Process concept  Process scheduling  Process scheduling  Interprocess communication Interprocess

8

Mutual Exclusion Mutual Exclusion Problem : Problem : StarvationStarvation

Also known as Also known as Indefinite Indefinite PostponementPostponement

DefinitionDefinition Indefinitely delaying the scheduling of a process Indefinitely delaying the scheduling of a process

in favour of other processes in favour of other processes

Cause Cause Usually a bias in a systems scheduling policies (a Usually a bias in a systems scheduling policies (a

bad scheduling algorithm)bad scheduling algorithm)

Solution Solution Implement some form of aging Implement some form of aging

Page 9: 1 Chapter 2.3 : Interprocess Communication Process concept  Process concept  Process scheduling  Process scheduling  Interprocess communication Interprocess

9

Another Problem : Another Problem : DeadlocksDeadlocks

Two (or more) processes are blocked Two (or more) processes are blocked waiting for an event that will never waiting for an event that will never occuroccur

Generally, A waits for B to do Generally, A waits for B to do something and B is waiting for Asomething and B is waiting for A

Both are not doing anything so both Both are not doing anything so both events never occurevents never occur

Page 10: 1 Chapter 2.3 : Interprocess Communication Process concept  Process concept  Process scheduling  Process scheduling  Interprocess communication Interprocess

10

How to Implement How to Implement Mutual ExclusionMutual Exclusion

Three possibilitiesThree possibilities Application: Application: programmer builds some programmer builds some

method method into the programinto the program Hardware:Hardware: special h/w instructions special h/w instructions

provided provided to implement MEto implement ME OS:OS: provides some services that provides some services that

can can be used by the programmerbe used by the programmer All schemes rely on some code forAll schemes rely on some code for

enter_critical_section, andenter_critical_section, and exit_critical_sectionexit_critical_section

These "functions" enclose the These "functions" enclose the critical sectioncritical section

Page 11: 1 Chapter 2.3 : Interprocess Communication Process concept  Process concept  Process scheduling  Process scheduling  Interprocess communication Interprocess

11

Application Mutual Application Mutual ExclusionExclusion

Application Mutual Exclusion isApplication Mutual Exclusion is implemented by the programmerimplemented by the programmer hard to get correct, andhard to get correct, and very inefficientvery inefficient

All rely on some form of busy All rely on some form of busy

waiting (process tests a condition, waiting (process tests a condition,

say a flag, and loops while the say a flag, and loops while the

condition remains the same) condition remains the same)

Page 12: 1 Chapter 2.3 : Interprocess Communication Process concept  Process concept  Process scheduling  Process scheduling  Interprocess communication Interprocess

12

ExampleExample ProducerProducer

produceproduceIf lock = 1 loop until lock = 0If lock = 1 loop until lock = 0lock=1lock=1put in bufferput in bufferlock=0lock=0

ConsumerConsumerIf lock = 1 loop until lock = 0If lock = 1 loop until lock = 0lock=1lock=1get from bufferget from bufferlock=0lock=0ConsumeConsume

Note: initially lock = 0

Page 13: 1 Chapter 2.3 : Interprocess Communication Process concept  Process concept  Process scheduling  Process scheduling  Interprocess communication Interprocess

13

Dekker’s AlgorithmDekker’s AlgorithmProgram Dekker;Program Dekker;Var Var turnturn : integer;: integer;

wantp, wantqwantp, wantq :boolean;:boolean;Procedure p;Procedure p;BeginBegin

repeatrepeatwantp := true;wantp := true;while wantq do if turn = 2 then begin wantp:= false; repeat until turn = while wantq do if turn = 2 then begin wantp:= false; repeat until turn =

1; wantp:=true end;1; wantp:=true end;CS;CS;turn := 2;turn := 2;wantp:= false;wantp:= false;NCS;NCS;

until false;until false;End;End;Procedure q;Procedure q;BeginBegin

repeatrepeatwantq2 := true;wantq2 := true;while wantp do if turn = 1 then begin wantq:= false; repeat until turn = while wantp do if turn = 1 then begin wantq:= false; repeat until turn =

2; wantq:=false end;2; wantq:=false end;CS;CS;turn := 1;turn := 1;wantq := false;wantq := false;NCS;NCS;

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

turn:= 1; wantp:= false; wantq:= false;turn:= 1; wantp:= false; wantq:= false;cobegin p; q coendcobegin p; q coend

End.End.

Page 14: 1 Chapter 2.3 : Interprocess Communication Process concept  Process concept  Process scheduling  Process scheduling  Interprocess communication Interprocess

14

Explanation of the Explanation of the AlgorithmAlgorithm

Procedure p;Procedure p;

BeginBegin

repeatrepeat

wantp := true;wantp := true; (* 1 *)(* 1 *)

while wantq do if turn = 2 then begin wantp:= false; repeat until turn = 1; while wantq do if turn = 2 then begin wantp:= false; repeat until turn = 1; wantp:=true end;wantp:=true end; (* 2 *)(* 2 *)

CS;CS;

turn := 2;turn := 2; (* 3 *)(* 3 *)

wantp := false;wantp := false; (* 4 *)(* 4 *)

NCS;NCS;

until false;until false;

End;End;

1.1. Process makes a request to enter CSProcess makes a request to enter CS

2.2. If the other process had made a request to enter CS before and if it is If the other process had made a request to enter CS before and if it is its turn then its turn then

Take back the request to enter CS by setting the “want” Take back the request to enter CS by setting the “want” variable to false”variable to false”

Wait for the other process to exit CS and change the turn Wait for the other process to exit CS and change the turn variablevariable

Make a new request to enter CS and then enter CSMake a new request to enter CS and then enter CS

3.3. Flip the turn variable so that now the other process can enter CSFlip the turn variable so that now the other process can enter CS

4.4. Set “want” variable to false to indicate that the process is now out of Set “want” variable to false to indicate that the process is now out of CSCS

Page 15: 1 Chapter 2.3 : Interprocess Communication Process concept  Process concept  Process scheduling  Process scheduling  Interprocess communication Interprocess

15

CommentsComments

Explicit control of transfer by a Explicit control of transfer by a turnturn variable. Hence; turn = 1 means P’s variable. Hence; turn = 1 means P’s turn, turn = 2 Q’s turnturn, turn = 2 Q’s turn

If a process is blocked, the other If a process is blocked, the other process can still goprocess can still go

Dekker’s algorithm is correct (prove it!)Dekker’s algorithm is correct (prove it!) It satisfies the mutual exclusion propertyIt satisfies the mutual exclusion property It is free from deadlock and starvationIt is free from deadlock and starvation

Page 16: 1 Chapter 2.3 : Interprocess Communication Process concept  Process concept  Process scheduling  Process scheduling  Interprocess communication Interprocess

16

Hardware ME : Hardware ME : Test and Set InstructionTest and Set Instruction

Perform an indivisible x:=r and r:=1 Perform an indivisible x:=r and r:=1

x is a local variablex is a local variable r is a global register set to 0 initiallyr is a global register set to 0 initially

repeat (test&set(x)) until x = 0;repeat (test&set(x)) until x = 0;

< critical section >< critical section >

r:= 0;r:= 0;

Page 17: 1 Chapter 2.3 : Interprocess Communication Process concept  Process concept  Process scheduling  Process scheduling  Interprocess communication Interprocess

17

Hardware ME : Hardware ME : Exchange InstructionExchange Instruction

Exchange: swap the values of x and rExchange: swap the values of x and r x is a local variablex is a local variable r is a global register set to 1 initiallyr is a global register set to 1 initially

x:= 0;x:= 0; repeat exchange(r, x) until x = 1;repeat exchange(r, x) until x = 1; < critical section >< critical section > exchange(r, x);exchange(r, x);

NoteNote: r:= 0 and x:= 1 when the process : r:= 0 and x:= 1 when the process isis in CSin CS

Page 18: 1 Chapter 2.3 : Interprocess Communication Process concept  Process concept  Process scheduling  Process scheduling  Interprocess communication Interprocess

18

Another Hardware ME : Another Hardware ME : Disabling InterruptsDisabling Interrupts

On a single CPU only one process is On a single CPU only one process is executedexecuted

Concurrency is achieved by interleaving Concurrency is achieved by interleaving execution (usually done using execution (usually done using interrupts)interrupts)

If you disable interrupts then you can be If you disable interrupts then you can be sure only one process will ever executesure only one process will ever execute

One process can lock a system or One process can lock a system or degrade performance greatlydegrade performance greatly

Page 19: 1 Chapter 2.3 : Interprocess Communication Process concept  Process concept  Process scheduling  Process scheduling  Interprocess communication Interprocess

19

Hardware ME Hardware ME CharacteristicsCharacteristics

AdvantagesAdvantages can be used by a single or multiple can be used by a single or multiple

processes (with shared memory)processes (with shared memory) simple and therefore easy to verifysimple and therefore easy to verify can support multiple critical sectionscan support multiple critical sections

DisadvantagesDisadvantages busy waiting is used is used ( (very very

importantimportant)) starvation is possiblestarvation is possible deadlock is possible (especially with deadlock is possible (especially with

priorities)priorities)

Page 20: 1 Chapter 2.3 : Interprocess Communication Process concept  Process concept  Process scheduling  Process scheduling  Interprocess communication Interprocess

20

Mutual Exclusion Mutual Exclusion Through OSThrough OS

SemaphoresSemaphores Message passingMessage passing

Page 21: 1 Chapter 2.3 : Interprocess Communication Process concept  Process concept  Process scheduling  Process scheduling  Interprocess communication Interprocess

21

SemaphoresSemaphores

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

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

operationsoperations

Page 22: 1 Chapter 2.3 : Interprocess Communication Process concept  Process concept  Process scheduling  Process scheduling  Interprocess communication Interprocess

22

Semaphore OperationsSemaphore Operations

Wait(s)Wait(s)

If s > 0 If s > 0 then s:= s - 1then s:= s - 1

else else block this block this processprocess

Signal(s)Signal(s)

If If there is a blocked process on there is a blocked process on this semaphorethis semaphore then then wake it wake it upup

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

Page 23: 1 Chapter 2.3 : Interprocess Communication Process concept  Process concept  Process scheduling  Process scheduling  Interprocess communication Interprocess

23

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 24: 1 Chapter 2.3 : Interprocess Communication Process concept  Process concept  Process scheduling  Process scheduling  Interprocess communication Interprocess

24

Producer - Consumer Producer - Consumer Problem: Solution by Problem: Solution by

SemaphoresSemaphores

Initially semaphoreInitially semaphore mutex mutex is 1 is 1

Produce

Wait(mutex)Put in bufferSignal(mutex)

Wait(mutex)Get from bufferSignal(mutex)

Consume

CS

Page 25: 1 Chapter 2.3 : Interprocess Communication Process concept  Process concept  Process scheduling  Process scheduling  Interprocess communication Interprocess

25

Another ExampleAnother Example Three processes all share a resource on whichThree processes all share a resource on which

one draws an Aone draws an A one draws a Bone draws a B one draws a Cone draws a C

Implement a form of Implement a form of synchronizationsynchronization so that the output so that the output appears ABCappears ABC

think();

draw_A();

think();

draw_B();

think();

draw_C();

Process A Process B Process C

Page 26: 1 Chapter 2.3 : Interprocess Communication Process concept  Process concept  Process scheduling  Process scheduling  Interprocess communication Interprocess

26

Semaphore b = 0, c = 0;Semaphore b = 0, c = 0;

think();

draw_A();

signal(b);

wait(b);

think();

draw_B();

signal(c);

wait(c);

think();

draw_C();

Process A Process B Process C

Page 27: 1 Chapter 2.3 : Interprocess Communication Process concept  Process concept  Process scheduling  Process scheduling  Interprocess communication Interprocess

27

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 Devise a ritual (protocol) that will allow the philosophers to

eat. The protocol should satisfy eat. 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 free from deadlock and absense of starvation from deadlock and absense of starvation

Figure is from Modern OS by Tanenbaum

Page 28: 1 Chapter 2.3 : Interprocess Communication Process concept  Process concept  Process scheduling  Process scheduling  Interprocess communication Interprocess

28

Dining Philosophers Solution – First Dining Philosophers Solution – First AttemptAttempt

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 29: 1 Chapter 2.3 : Interprocess Communication Process concept  Process concept  Process scheduling  Process scheduling  Interprocess communication Interprocess

29

Comments on First Comments on First AttemptAttempt

Mutual exclusion is implemented by a Mutual exclusion is implemented by a binary semaphore binary semaphore forkfork

Deadlock is possible if all 5 philosophers Deadlock is possible if all 5 philosophers take the left forks simultaneously then all take the left forks simultaneously then all would wait for the right forkwould wait for 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 Two of them can eat, one holds a fork and the

other just sitsother just sits One philosopher can eat and the other 3 can One philosopher can eat and the other 3 can

hold their left forkshold their left forks

Page 30: 1 Chapter 2.3 : Interprocess Communication Process concept  Process concept  Process scheduling  Process scheduling  Interprocess communication Interprocess

30

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 31: 1 Chapter 2.3 : Interprocess Communication Process concept  Process concept  Process scheduling  Process scheduling  Interprocess communication Interprocess

31

Message PassingMessage Passing

Provides synchronization and Provides synchronization and

information exchangeinformation exchange

Message Operations:Message Operations:

send(destination, &message)send(destination, &message)

receive (source, &message) receive (source, &message)

Page 32: 1 Chapter 2.3 : Interprocess Communication Process concept  Process concept  Process scheduling  Process scheduling  Interprocess communication Interprocess

32

Producer - Consumer Producer - Consumer Problem Using MessagesProblem Using Messages#define N 100 /*number of message #define N 100 /*number of message

slots*/slots*/

producer( )producer( ){int item; message m;{int item; message m; while (TRUE) {while (TRUE) {

produce_item(&item);produce_item(&item);receive(consumer,&m);receive(consumer,&m);build_message(&m, item);build_message(&m, item);send(consumer,&m);send(consumer,&m);

}}}}

Page 33: 1 Chapter 2.3 : Interprocess Communication Process concept  Process concept  Process scheduling  Process scheduling  Interprocess communication Interprocess

33

Consumer( )Consumer( ){int item; message m;{int item; message m; for (i=0; i<N; i++) for (i=0; i<N; i++)

send(producer,&m);send(producer,&m); while (TRUE) {while (TRUE) {

receive(producer,&m);receive(producer,&m);extract_item(&m,&item);extract_item(&m,&item);send(producer,&m);send(producer,&m);consume_item(item);consume_item(item);

}}}}