Dining philosopher monitor_2

50
Dining Philosopher Problem Dining Philosopher Problem By By CHITRAKANT BANCHHOR CHITRAKANT BANCHHOR IT, IT, MITCOE MITCOE, Pune Pune

Transcript of Dining philosopher monitor_2

Page 1: Dining philosopher monitor_2

Dining Philosopher ProblemDining Philosopher Problem

ByByCHITRAKANT BANCHHORCHITRAKANT BANCHHOR

IT,IT, MITCOEMITCOE,, PunePune

ByByCHITRAKANT BANCHHORCHITRAKANT BANCHHOR

IT,IT, MITCOEMITCOE,, PunePune

Page 2: Dining philosopher monitor_2

ReferencesReferences

•• Operating system concepts, 6th edition byOperating system concepts, 6th edition by Silberschatz A, Galvin andSilberschatz A, Galvin andGagne.Gagne.

•• Operating Systems, 4th edition by William StallingsOperating Systems, 4th edition by William Stallings

•• Operating Systems ByOperating Systems By DeitelDeitel

2

•• Operating system concepts, 6th edition byOperating system concepts, 6th edition by Silberschatz A, Galvin andSilberschatz A, Galvin andGagne.Gagne.

•• Operating Systems, 4th edition by William StallingsOperating Systems, 4th edition by William Stallings

•• Operating Systems ByOperating Systems By DeitelDeitel

Page 3: Dining philosopher monitor_2

IntroductionIntroduction

E.W.E.W. DijkstraDijkstra: The dining philosopher problem was first: The dining philosopher problem was firstmade up bymade up by DijkstraDijkstra

•• SignificanceSignificance::

•• Designing deadlock and starvationDesigning deadlock and starvation--free solutions to the complex problems infree solutions to the complex problems incomputer science.computer science.

Page 4: Dining philosopher monitor_2

The ProblemThe Problem

0

14

100

1

23

4

4

3

2

1

2 3

4

Page 5: Dining philosopher monitor_2

•• Think and Eat statesThink and Eat states::

A philosopher’s life is simplified into two states:A philosopher’s life is simplified into two states: think and eatthink and eat..

Every philosopher indefinitely repeats these states.Every philosopher indefinitely repeats these states.

•• Assumptions:Assumptions:

A philosopher cannot continuouslyA philosopher cannot continuously eateat oror thinkthink..

A philosopher must change his or her state every once in a while.A philosopher must change his or her state every once in a while.

•• Think and Eat statesThink and Eat states::

A philosopher’s life is simplified into two states:A philosopher’s life is simplified into two states: think and eatthink and eat..

Every philosopher indefinitely repeats these states.Every philosopher indefinitely repeats these states.

•• Assumptions:Assumptions:

A philosopher cannot continuouslyA philosopher cannot continuously eateat oror thinkthink..

A philosopher must change his or her state every once in a while.A philosopher must change his or her state every once in a while.

Page 6: Dining philosopher monitor_2

0

14

1 0

Left and Right forks:Left and Right forks: A philosopher must seize the two forks.A philosopher must seize the two forks.

RulesRules

23

4

4

3

2

Complicated case:Complicated case: The case becomes complicated when the rule thatThe case becomes complicated when the rule thatevery philosopher has to use two forks to eat rice must be observed toevery philosopher has to use two forks to eat rice must be observed toarrive at an acceptable solution.arrive at an acceptable solution.

Page 7: Dining philosopher monitor_2

Shared resourcesShared resources

A computer processA computer process

Computer system analogyComputer system analogy

Synchronization not required:Synchronization not required:

When there are enough forks, the processes are independent and there isWhen there are enough forks, the processes are independent and there isno need for synchronizationno need for synchronization

Page 8: Dining philosopher monitor_2

0

1

23

4

1 0

4

3

2

0

1

2 3

4

1.1. Plates are numbered in a counter clockwise direction fromPlates are numbered in a counter clockwise direction from 0 to 40 to 4

2.2. PhilosopherPhilosopher ii,, ii = 0 , 1 , … , and 4= 0 , 1 , … , and 4, is sitting at the table so as to use plate number, is sitting at the table so as to use plate number ii

3.3. ForksForks are numbered so that fork numberare numbered so that fork number ii,, ii = 0, 1 , … , 4 , is next to= 0, 1 , … , 4 , is next to philosopherphilosopher ii atathis or her left sidehis or her left side

Page 9: Dining philosopher monitor_2

Dining Philosopher Problem solutionDining Philosopher Problem solution

Page 10: Dining philosopher monitor_2

First AttemptFirst Attempt

1. Start eating: If two forks are successfully grabbed by philosophersthen they start eating.

2. Puts down a fork: The philosopher puts down the forks one at atime.

3. Grab left fork: It does not really matter which fork is taken first by aphilosopher, so, we will assume the fork on his left hand side isgrabbed first.

1. Start eating: If two forks are successfully grabbed by philosophersthen they start eating.

2. Puts down a fork: The philosopher puts down the forks one at atime.

3. Grab left fork: It does not really matter which fork is taken first by aphilosopher, so, we will assume the fork on his left hand side isgrabbed first.

Page 11: Dining philosopher monitor_2

Assumed Primitive operationsAssumed Primitive operations

1. grab_fork( int fork_no ) : To grab the nominated fork.

2. put _fork ( int fork_no ) : To put down the nominated fork.

Proper care is taken, in writing these procedures, to avoidProper care is taken, in writing these procedures, to avoidrace conditions when grabbing or putting down a fork.race conditions when grabbing or putting down a fork.

Page 12: Dining philosopher monitor_2

void philosopher ( int i ) /* i = 0, 1, …, n-1 is the philosopher number */{

while (1) { /* Do this loop forever */

Think; /* Think for a while */

grab_fork(i); /* Grab left fork */

grab_fork((i+1)%n); /* Grab right fork */

Eat; /* Eat as you like */

put_fork(i); /* Put left fork */

put_fork((i+1)%n); /* Put right fork */}

}

void philosopher ( int i ) /* i = 0, 1, …, n-1 is the philosopher number */{

while (1) { /* Do this loop forever */

Think; /* Think for a while */

grab_fork(i); /* Grab left fork */

grab_fork((i+1)%n); /* Grab right fork */

Eat; /* Eat as you like */

put_fork(i); /* Put left fork */

put_fork((i+1)%n); /* Put right fork */}

}

This procedure is executed by each philosopher.This procedure is executed by each philosopher.

TheThe grab_forkgrab_fork andand put_forkput_fork procedures are assumed to beprocedures are assumed to be race freerace free procedures.procedures.

Page 13: Dining philosopher monitor_2

ScenarioScenario –– 1:1:

• Each philosopher has taken left fork: All philosopher processes get to thepoint where each one has taken the left fork

• Now each one tries to take the right fork, executing grab_fork((i+1)%n).

Page 14: Dining philosopher monitor_2

0

Deadlock:Deadlock:

1.1. In such circumstances, no fork is available and all philosophers will enter aIn such circumstances, no fork is available and all philosophers will enter await state.wait state.

2.2. This will result in aThis will result in a circularcircular--wait conditionwait condition which in turn indicates awhich in turn indicates a deadlockdeadlock..

1

23

4

1 0

4

3

2

Page 15: Dining philosopher monitor_2

Processes synchronized: ( 0 and 3 and 2 and 4 )2 and 4 )

Processes 0 and 3 and 2 and 42 and 4 are so synchronizedsynchronized that:

Whenever 0 and 30 and 3 are eating 2 and 42 and 4 are thinking

and as soon as 0 and 30 and 3 put down their forks 2 and 42 and 4 grab them immediately.

Also, whenever 2 and 42 and 4 put down their forks 0 and 30 and 3 grab them immediately.

ScenarioScenario –– 2:2:

Processes synchronized: ( 0 and 3 and 2 and 4 )2 and 4 )

Processes 0 and 3 and 2 and 42 and 4 are so synchronizedsynchronized that:

Whenever 0 and 30 and 3 are eating 2 and 42 and 4 are thinking

and as soon as 0 and 30 and 3 put down their forks 2 and 42 and 4 grab them immediately.

Also, whenever 2 and 42 and 4 put down their forks 0 and 30 and 3 grab them immediately.

00

1

22 33

44

1 0

4

3

2

Page 16: Dining philosopher monitor_2

Starvation:Starvation:

001

22 33

44

1 0

4

3

2

Philosopher 1 will starve to deathPhilosopher 1 will starve to death :: If this cycle repeats forever,If this cycle repeats forever, Philosopher 1Philosopher 1will starve to death and, thus, a starvation state is possible.will starve to death and, thus, a starvation state is possible.

Page 17: Dining philosopher monitor_2

Second AttemptSecond Attempt

In this attempt, we will focus on removing the possibility of deadlockfrom the Attempt 1’s solution.

Avoid Hold & Wait condition:Avoid Hold & Wait condition:

Philosopher(i) :if ( get_both_forks || not_get_any_forks ){

Possibility of hold and wait is removed}

Page 18: Dining philosopher monitor_2

New Procedure :New Procedure :

grab_forksgrab_forks( int( int philosopher_nophilosopher_no ))

1. Suppose we have prepared this as a new race-free procedure.

2. This is used to grab both forks at one time, whenever possible.

1. Suppose we have prepared this as a new race-free procedure.

2. This is used to grab both forks at one time, whenever possible.

Page 19: Dining philosopher monitor_2

void philosopher ( int i ) /* i = 0, 1, …, n-1 is the philosopher number */{

while (1) { /* Do this loop forever */

Think; /* Think for a while */

grab_forks(i); /* Grab both forks */

Eat; /* Eat as you like */

put_fork(i); /* Put left fork down*/

put_fork((i+1)%n); /* Put right fork down*/}

}

void philosopher ( int i ) /* i = 0, 1, …, n-1 is the philosopher number */{

while (1) { /* Do this loop forever */

Think; /* Think for a while */

grab_forks(i); /* Grab both forks */

Eat; /* Eat as you like */

put_fork(i); /* Put left fork down*/

put_fork((i+1)%n); /* Put right fork down*/}

}

Deadlock freeDeadlock free:: This algorithm removes the possibility of a holdThis algorithm removes the possibility of a hold--andand--waitwaitsituation. Hence, it is deadlock free.situation. Hence, it is deadlock free.

StarvationStarvation:: IfIf put_forkput_fork((ii)) simply puts a fork down, the starvation possibilitysimply puts a fork down, the starvation possibilitypersists, similar to Attempt 1.persists, similar to Attempt 1.

Page 20: Dining philosopher monitor_2

MonitorMonitor

ByByCHITRAKANT BANCHHORCHITRAKANT BANCHHOR

IT, SCOE,IT, SCOE, PunePune

ByByCHITRAKANT BANCHHORCHITRAKANT BANCHHOR

IT, SCOE,IT, SCOE, PunePune

Page 21: Dining philosopher monitor_2

ReferencesReferences

•• Operating system concepts, 6th edition byOperating system concepts, 6th edition by Silberschatz A, Galvin andSilberschatz A, Galvin andGagne.Gagne.

•• Operating Systems, 4th edition by William StallingsOperating Systems, 4th edition by William Stallings

21

Page 22: Dining philosopher monitor_2

MonitorMonitor--Based IPCBased IPC

Page 23: Dining philosopher monitor_2

OverviewOverview

•• Monitor is a programmingMonitor is a programming--language construct provideslanguage construct providesfunctionalities like semaphores.functionalities like semaphores.

The monitor construct is implemented in languages:The monitor construct is implemented in languages:

1.1. PascalPascal2.2. PascalPascal--PlusPlus3.3. ModulaModula--224.4. ModulaModula--335.5. JavaJava

1.1. PascalPascal2.2. PascalPascal--PlusPlus3.3. ModulaModula--224.4. ModulaModula--335.5. JavaJava

Page 24: Dining philosopher monitor_2

Monitor with SignalMonitor with Signal

A monitor is a software module consists of :A monitor is a software module consists of :

Procedure – 1 Procedure – 2

………… Procedure – N

ProceduresProcedures

Procedure – 1 Procedure – 2

………… Procedure – N

An initialization sequence

A local data

Initialization sequence ofInitialization sequence ofvariables ( index and flags etc. )variables ( index and flags etc. )

Monitor specific dataMonitor specific data

Page 25: Dining philosopher monitor_2

Monitor :Monitor : characteristicscharacteristics

Local Data : accessible only by the monitor’s procedures and not byany external procedure.

MonitorProcedure

Proc - 1Proc - 1

Proc - 2Proc - 2

MonitorProcedure

A process enters the monitor by invoking one of its procedures.

Local dataLocal data

Page 26: Dining philosopher monitor_2

Proc - 1Proc - 1

Monitor

P1 P2

Monitor :Monitor : One process at a timeOne process at a time

Only one process may be executing in the monitor at a time;Only one process may be executing in the monitor at a time;

any other processes that have invoked the monitor are blocked waitingany other processes that have invoked the monitor are blocked waitingfor the monitor to become available.for the monitor to become available.

Proc - 1Proc - 1

Proc - 2Proc - 2

Page 27: Dining philosopher monitor_2

Monitor :Monitor : data variablesdata variables

•• Data variablesData variables in the monitor can be accessed by only onein the monitor can be accessed by only oneprocess at a time.process at a time.

•• Example:Example:•• a shared data structure can be protected by placing it in a monitor.a shared data structure can be protected by placing it in a monitor.

•• Data variablesData variables in the monitor can be accessed by only onein the monitor can be accessed by only oneprocess at a time.process at a time.

•• Example:Example:•• a shared data structure can be protected by placing it in a monitor.a shared data structure can be protected by placing it in a monitor.

Page 28: Dining philosopher monitor_2

Proc - 1Proc - 1

Proc - 2Proc - 2

Monitor

P1 P2Data

Monitor :Monitor : mutual exclusionmutual exclusion

Proc - 2Proc - 2

If the data in a monitor represent some resource, then the monitorIf the data in a monitor represent some resource, then the monitorprovides a mutual exclusion facility for accessing the resource.provides a mutual exclusion facility for accessing the resource.

Page 29: Dining philosopher monitor_2

Monitor includesMonitor includes synchronization toolsynchronization tool forfor concurrent processingconcurrent processing..

Condition variable:Condition variable:

A monitor supports synchronization by the use of condition variables.A monitor supports synchronization by the use of condition variables.

Condition variables are contained within the monitor and accessible onlyCondition variables are contained within the monitor and accessible onlywithin the monitor.within the monitor.

Monitor :Monitor : synchronization toolsynchronization tool

Monitor includesMonitor includes synchronization toolsynchronization tool forfor concurrent processingconcurrent processing..

Condition variable:Condition variable:

A monitor supports synchronization by the use of condition variables.A monitor supports synchronization by the use of condition variables.

Condition variables are contained within the monitor and accessible onlyCondition variables are contained within the monitor and accessible onlywithin the monitor.within the monitor.

Page 30: Dining philosopher monitor_2

Condition VariableCondition Variable

example:example:if ( x == true ) {if ( x == true ) {

allowed to proceedallowed to proceed}}else {else {

wait()wait()}}

Condition VariableCondition Variable

example:example:if ( x == true ) {if ( x == true ) {

allowed to proceedallowed to proceed}}else {else {

wait()wait()}}

P 1P 1P 2P 2

Condition VariableCondition Variable

example:example:if ( x == true ) {if ( x == true ) {

allowed to proceedallowed to proceed}}else {else {

wait()wait()}}

Condition VariableCondition Variable

example:example:if ( x == true ) {if ( x == true ) {

allowed to proceedallowed to proceed}}else {else {

wait()wait()}}

Monitor

Page 31: Dining philosopher monitor_2

Monitor :Monitor : Condition variablesCondition variables

•• Condition variables are a special data type in monitor.Condition variables are a special data type in monitor.

•• Conditions are operated on by two functions:Conditions are operated on by two functions:

1.1. cwaitcwait(c)(c)2.2. csignalcsignal(c)(c)1.1. cwaitcwait(c)(c)2.2. csignalcsignal(c)(c)

Page 32: Dining philosopher monitor_2

cwaitcwait ( C )( C )

cwaitcwait ( C )( C ){{

}}………..

P1

1.1. Suspends execution of the calling processSuspends execution of the calling processon conditionon condition CC

2.2. The monitor is now available for useThe monitor is now available for useby another processby another process

cwaitcwait ( C )( C ){{

}}………..

2.2. The monitor is now available for useThe monitor is now available for useby another processby another process

Page 33: Dining philosopher monitor_2

csignalcsignal ( c )( c ) ::

Resume execution of some process blocked after aResume execution of some process blocked after a cwaitcwait on theon thesame condition.same condition.

if ( there are more than one processes waiting on C ){

select one process}else if ( no process waiting on C ) {

; /* do nothing */}

if ( there are more than one processes waiting on C ){

select one process}else if ( no process waiting on C ) {

; /* do nothing */}

Page 34: Dining philosopher monitor_2

Structure of a MonitorStructure of a Monitor

Page 35: Dining philosopher monitor_2

Dining Philosopher problem:Dining Philosopher problem:Solution Using MonitorSolution Using Monitor

Page 36: Dining philosopher monitor_2

•• A monitor is used to control access to state variables andA monitor is used to control access to state variables andcondition variables.condition variables.

Use of monitorUse of monitor

Page 37: Dining philosopher monitor_2

Monitor :Monitor :not included componentsnot included components

forksforks

RiceRiceare notare not part of the monitorpart of the monitor

If they were, then the entire act of eating would have to be a monitorIf they were, then the entire act of eating would have to be a monitorprocedure and only one philosopher could eat at a time.procedure and only one philosopher could eat at a time.

Page 38: Dining philosopher monitor_2

Monitor :Monitor : proceduresprocedures

•• Grab_forksGrab_forks()()

•• Put_forksPut_forks()()

Page 39: Dining philosopher monitor_2

Assumed dataAssumed data

The number of philosophers :The number of philosophers : NUM_OF_PHILSNUM_OF_PHILS

Philosopher states :Philosopher states : THINKING,THINKING, HUNGRY,HUNGRY, EATINGEATING

Page 40: Dining philosopher monitor_2

Condition variableCondition variable

ConditionVariable

For each philosopher there is a condition variableFor each philosopher there is a condition variable

if ( forks are not available when a philosopher is hungry ) {

A philosopher has to wait on a condition variable}

Page 41: Dining philosopher monitor_2

A Philosopher’s moveA Philosopher’s move

Check states ofboth neighbors

If either oneor both eating

Philosopher [ i ] wants to eat

Finished eating :Finished eating :1.1. give each neighbor a chance to eat2. Also become candidate to eat after each neighbors’ turn

wait ()

Start_Eating

Page 42: Dining philosopher monitor_2

void philosopher ( int i ) /* i = 0, 1, …, n-1 is the philosopher number */{

while (1) { /* Do this loop forever */

Think; /* Think for a while */

grab_forks(i); /* Grab both forks */

Eat; /* Eat as you like */

put_forks(i); /* Put forks down*/}

}

PhilosopherPhilosopher

void philosopher ( int i ) /* i = 0, 1, …, n-1 is the philosopher number */{

while (1) { /* Do this loop forever */

Think; /* Think for a while */

grab_forks(i); /* Grab both forks */

Eat; /* Eat as you like */

put_forks(i); /* Put forks down*/}

}

Page 43: Dining philosopher monitor_2

MONITORMONITOR

DATA:

INITIALIZATION:

MONITOR PROCEDURES:MONITOR PROCEDURES:

Page 44: Dining philosopher monitor_2

DataData

condition can_eat[ NUM_OF_PHILS ] ;

enum states {THINKING,HUNGRY,EATING

} state [ NUM_OF_PHILS - 1 ];

int index;

condition can_eat[ NUM_OF_PHILS ] ;

enum states {THINKING,HUNGRY,EATING

} state [ NUM_OF_PHILS - 1 ];

int index;

Page 45: Dining philosopher monitor_2

Initialization:Initialization:

for ( index = 0; index < NUM_OF_PHILS; index++ ) {

flags [ index ] = THINKING;}

Initialize all philosophers’ flag as thinking.Initialize all philosophers’ flag as thinking.

This means let all philosophers are initially in thinking state.This means let all philosophers are initially in thinking state.

Page 46: Dining philosopher monitor_2

MONITOR PROCEDURES:MONITOR PROCEDURES:

1.1. /* request the right to pickup fork and eat *//* request the right to pickup fork and eat */voidvoid grab_forkgrab_fork(( intint ii ););

2. /* announce that we're finished, give others a chance */2. /* announce that we're finished, give others a chance */voidvoid put_downput_down( int( int ii ););

Page 47: Dining philosopher monitor_2

1.1. Procedure :Procedure : grab_forkgrab_fork()()

/* request the right to pickup forks and eat */

entry void grab_fork( int i ) {

state [ i ] = HUNGRY ; /* announce that we're hungry */

/* if neighbors aren't eating, proceed */if ( ( state [ i – 1 mod NUM_OF_PHILS ] != EATING ) &&

( state [ i + 1 mod NUM_OF_PHILS ] != EATING ) ) {if ( ( state [ i – 1 mod NUM_OF_PHILS ] != EATING ) &&

( state [ i + 1 mod NUM_OF_PHILS ] != EATING ) ) {

state [ i ] = EATING ;

}

elsecan_eat [ i ] . cwait ; /* otherwise wait for them */

state[ i ] = EATING; /* get signal and resumeget signal and resume: ready to eat now */

}

Page 48: Dining philosopher monitor_2

2.2. Procedure :Procedure : putdownputdown

/* announce that we're finished, give others a chance */

entry void putdown ( int i ) {

state[ i ] = THINKING; /* announce that we're done */

/* give left neighbor a chance to eat */

if (( state [ i - 1 mod NUM_OF_PHILS ] == HUNGRY ) &&( state [ i - 2 mod NUM_OF_PHILS ] != EATING ) )

{can_eat [ i - 1 mod NUM_PHILS ] . signal ;

}

if (( state [ i - 1 mod NUM_OF_PHILS ] == HUNGRY ) &&( state [ i - 2 mod NUM_OF_PHILS ] != EATING ) )

{can_eat [ i - 1 mod NUM_PHILS ] . signal ;

}/* give right neighbor a chance to eat */if ( ( state [ i + 1 mod NUM_OF_PHILS ] == HUNGRY )

&& ( state [ i + 2 mod NUM_PHILS ] != EATING ) ){

can_eat [ i + 1 mod NUM_PHILS] . csignal ;}

}

Page 49: Dining philosopher monitor_2
Page 50: Dining philosopher monitor_2

Thank You!Thank You!Thank You!Thank You!

50