SlideShare a Scribd company logo
Group members:
ROLL NO:
ROLL NO:
ROLL NO:
ROLL NO:
ROLL NO:
Group No 02
University of Azad Jammu & Kashmir
Neelum Campus
BSCS V Semester, 2014-18
Operating System
Topic: Dining Philosophers
Presented By:
Mansoor Bashir
Dining Philosopher’s Problem
• Philosophers eat/think
• Eating needs two forks
• Pick one fork at a time
Dining Philosophers Problem
Five philosophers who spend their lives
just thinking and eating.
Only five chopsticks are available to the
philosophers
Dining Philosophers Problem
Each philosopher thinks. When he
becomes hungry, he sits down and
picks up the two chopsticks that are
closest to him and eats.
After a philosopher finishes eating, he
puts down the chopsticks and starts to
think.
Dining-Philosophers Problem
Dining-Philosophers Problem
Shared data : semaphore chopstick[5];
// Initialized to 1
Dining-Philosophers Problem
Philosopher i
do {
wait(chopstick[i])
wait(chopstick[(i+1)% 5])
eat
signal(chopstick[i]);
signal(chopstick[(i+1)% 5])
think
} while (1);
Possibility of Deadlock
If all philosophers become
hungry at the same time and
pick up their left chopstick, a
deadlock occurs.
17 December 2018
Possible Solutions
 Allow at most four philosophers
to be sitting simultaneously at
the table.
 Allow a philosopher to pick up
his/her chopsticks only if both
chopsticks are available (to do
this she must pick them up in a
critical section)
17 December 2018
Possible Solutions
Use an asymmetric solution; that is,
an odd philosopher picks up first
her left chopstick, whereas an even
philosopher picks up her right
chopstick and then her left
chopstick.
17 December 2018
Possibility of
Starvation
 Two philosophers who are fast
eaters and fast thinkers, and
lock the chopsticks before
others every time.
17 December 2018
Critical Regions
A critical region is a section of
code that is always executed
under mutual exclusion.
17 December 2018
Critical Regions
 They consist of two parts:
1.Variables that must be
accessed under mutual
exclusion.
2.A new language statement
that identifies a critical region
in which the variables are
accessed.
Dining philosophers
Who eats?
Types of Semaphores
 Counting semaphore – integer value
can range over an unrestricted integer
domain.
 Binary semaphore – integer value
cannot be > 1; can be simpler to
implement.
Implementing a Counting Semaphore
 Data structures
binary-semaphore S1, S2;
int C;
 Initialization
S1 = 1
S2 = 0
C = initial value of semaphore S
wait(S1);
C--;
if (C < 0) {
signal(S1);
wait(S2);
}
signal(S1);
Implementing a Counting Semaphore
wait(S):
wait(S1);
C++;
if (C <= 0)
signal(S2);
else
signal(S1);
Implementing a Counting Semaphore
signal(S):
i. Deterministic algorithms
ii. Randomized algorithm
Algorithms
Two Algorithm for dining Philosophers:
Two goals to achieve in solving the problem:
Deadlock free -- if at any time there is a hungry
philosopher, then eventually some philosopher will
eat.
Lockout free -- every hungry philosopher eventually
gets to eat.
The configuration of philosophers and sticks for the
case of n = 5 is illustrated below:
1. Deterministic algorithms:
As is proven in D. Lehman and M. O. Rabin's paper in
1981, no fully distributed and symmetric deterministic
algorithm for dining philosophers is possible. We can
prove it using the following example by introducing the
role of an adversary.
There can be an evil adversary, who contrives to
produce deadlock. For example, the adversary can
come up with the following "clever" strategy:
 All n philosophers become hungry at the same
moment
 They each pick up their left fork simultaneously
 because of the symmetry and the fact that each philosopher's
behavior is strictly deterministic, they have no choice but to put
down their sticks and try again later still precisely at the same
time.
By repeating this cycle constantly, the adversary will be able to
bring deadlock into this problem, thus makes any deterministic
algorithms fail to work.
Continue….
2. Randomized algorithm:
 Fork Available[i] is a Boolean variable for each Pi - Pi+1 pair,
which indicates whether the fork between them is available.
 The subtractions and additions are to be interpreted modulo n
We toss a coin when the hungry philosopher decides whether
to pick up the left fork or the right one first.
This randomization prevents any evil adversary's scheme. We
can show that the algorithm is deadlock free.
Continue….
The proof is based on that the coin tosses made by
philosophers are independent random events. Thus,
even if the adversary scheduler tries to bring on
deadlock, a combination of tosses will finally arise that
enables some philosopher to obtain two sticks. As the
index number (0,1,...i) attached to a philosopher is for
naming only, the algorithm is totally symmetric.
Continue….
However, this algorithm is not lockout free. There can
exist a very greedy philosopher Pi, and he tries to
prevent his neighbor from eating by always beating him
in the race of picking up the stick. Therefore, we need
some more parameters to improve this algorithm. We
can add two variables for each pair of philosophers, one
lets Pi to inform Pi+1 of his desire to eat, and vice versa.
The other shows which of the two eats last. In this way,
we can achieve both the deadlock free and lockout free
Continue….
17 December 2018
Monitor
Dining Philosophers Example
monitor dp
{
enum {thinking, hungry, eating} state[5];
condition self[5];
void pickup(int i) // Following slides
void putdown(int i) // Following slides
void test(int i) // Following slides
void init() {
for (int i = 0; i < 5; i++)
state[i] = thinking;
}
}
17 December 2018
Dining Philosophers
void pickup(int i) {
state[i] = hungry;
test(i);
if (state[i] != eating)
self[i].wait();
}
17 December 2018
void putdown(int i) {
state[i] = thinking;
// test left and right
// neighbors
test((i+4) % 5);
test((i+1) % 5);
}
Dining Philosophers
17 December 2018
void test(int i) {
if ((state[(i+4)%5]!= eating)
&& (state[i] == hungry) &&
(state[(i+1)%5]!= eating))
{
state[i] = eating;
self[i].signal();
}
}
Dining Philosophers
THANK
YOU

More Related Content

What's hot

Operating system 25 classical problems of synchronization
Operating system 25 classical problems of synchronizationOperating system 25 classical problems of synchronization
Operating system 25 classical problems of synchronization
Vaibhav Khanna
 
Job sequencing with deadline
Job sequencing with deadlineJob sequencing with deadline
Job sequencing with deadline
Arafat Hossan
 
Greedy Algorihm
Greedy AlgorihmGreedy Algorihm
Greedy Algorihm
Muhammad Amjad Rana
 
Operating system 24 mutex locks and semaphores
Operating system 24 mutex locks and semaphoresOperating system 24 mutex locks and semaphores
Operating system 24 mutex locks and semaphores
Vaibhav Khanna
 
Critical section problem in operating system.
Critical section problem in operating system.Critical section problem in operating system.
Critical section problem in operating system.
MOHIT DADU
 
First-Come-First-Serve (FCFS)
First-Come-First-Serve (FCFS)First-Come-First-Serve (FCFS)
First-Come-First-Serve (FCFS)nikeAthena
 
Top down parsing
Top down parsingTop down parsing
Top down parsing
ASHOK KUMAR REDDY
 
Parsing
ParsingParsing
Parsing
khush_boo31
 
Memory Management in OS
Memory Management in OSMemory Management in OS
Memory Management in OS
vampugani
 
Binary Semaphore
Binary SemaphoreBinary Semaphore
Binary Semaphore
Manash Kumar Mondal
 
RECURSIVE DESCENT PARSING
RECURSIVE DESCENT PARSINGRECURSIVE DESCENT PARSING
RECURSIVE DESCENT PARSING
Jothi Lakshmi
 
INTER PROCESS COMMUNICATION (IPC).pptx
INTER PROCESS COMMUNICATION (IPC).pptxINTER PROCESS COMMUNICATION (IPC).pptx
INTER PROCESS COMMUNICATION (IPC).pptx
LECO9
 
Peterson Critical Section Problem Solution
Peterson Critical Section Problem SolutionPeterson Critical Section Problem Solution
Peterson Critical Section Problem Solution
Bipul Chandra Kar
 
Interrupts
InterruptsInterrupts
Process synchronization in Operating Systems
Process synchronization in Operating SystemsProcess synchronization in Operating Systems
Process synchronization in Operating Systems
Ritu Ranjan Shrivastwa
 
Inter Process Communication Presentation[1]
Inter Process Communication Presentation[1]Inter Process Communication Presentation[1]
Inter Process Communication Presentation[1]Ravindra Raju Kolahalam
 
Process synchronization
Process synchronizationProcess synchronization
Process synchronization
Syed Hassan Ali
 
Recognition-of-tokens
Recognition-of-tokensRecognition-of-tokens
Recognition-of-tokens
Dattatray Gandhmal
 
Process Scheduling
Process SchedulingProcess Scheduling

What's hot (20)

Operating system 25 classical problems of synchronization
Operating system 25 classical problems of synchronizationOperating system 25 classical problems of synchronization
Operating system 25 classical problems of synchronization
 
Job sequencing with deadline
Job sequencing with deadlineJob sequencing with deadline
Job sequencing with deadline
 
Greedy Algorihm
Greedy AlgorihmGreedy Algorihm
Greedy Algorihm
 
Operating system 24 mutex locks and semaphores
Operating system 24 mutex locks and semaphoresOperating system 24 mutex locks and semaphores
Operating system 24 mutex locks and semaphores
 
Critical section problem in operating system.
Critical section problem in operating system.Critical section problem in operating system.
Critical section problem in operating system.
 
First-Come-First-Serve (FCFS)
First-Come-First-Serve (FCFS)First-Come-First-Serve (FCFS)
First-Come-First-Serve (FCFS)
 
Top down parsing
Top down parsingTop down parsing
Top down parsing
 
Parsing
ParsingParsing
Parsing
 
Memory Management in OS
Memory Management in OSMemory Management in OS
Memory Management in OS
 
Binary Semaphore
Binary SemaphoreBinary Semaphore
Binary Semaphore
 
Pumping lemma
Pumping lemmaPumping lemma
Pumping lemma
 
RECURSIVE DESCENT PARSING
RECURSIVE DESCENT PARSINGRECURSIVE DESCENT PARSING
RECURSIVE DESCENT PARSING
 
INTER PROCESS COMMUNICATION (IPC).pptx
INTER PROCESS COMMUNICATION (IPC).pptxINTER PROCESS COMMUNICATION (IPC).pptx
INTER PROCESS COMMUNICATION (IPC).pptx
 
Peterson Critical Section Problem Solution
Peterson Critical Section Problem SolutionPeterson Critical Section Problem Solution
Peterson Critical Section Problem Solution
 
Interrupts
InterruptsInterrupts
Interrupts
 
Process synchronization in Operating Systems
Process synchronization in Operating SystemsProcess synchronization in Operating Systems
Process synchronization in Operating Systems
 
Inter Process Communication Presentation[1]
Inter Process Communication Presentation[1]Inter Process Communication Presentation[1]
Inter Process Communication Presentation[1]
 
Process synchronization
Process synchronizationProcess synchronization
Process synchronization
 
Recognition-of-tokens
Recognition-of-tokensRecognition-of-tokens
Recognition-of-tokens
 
Process Scheduling
Process SchedulingProcess Scheduling
Process Scheduling
 

More from .AIR UNIVERSITY ISLAMABAD

Risk Assessment
Risk AssessmentRisk Assessment
Risk Assessment
.AIR UNIVERSITY ISLAMABAD
 
Mission ,Vision statement, and strategies of Unicef
Mission ,Vision statement, and strategies of UnicefMission ,Vision statement, and strategies of Unicef
Mission ,Vision statement, and strategies of Unicef
.AIR UNIVERSITY ISLAMABAD
 
Pipelining & All Hazards Solution
Pipelining  & All Hazards SolutionPipelining  & All Hazards Solution
Pipelining & All Hazards Solution
.AIR UNIVERSITY ISLAMABAD
 
Project Management System
Project Management SystemProject Management System
Project Management System
.AIR UNIVERSITY ISLAMABAD
 
Interfacing With High Level Programming Language
Interfacing With High Level Programming Language Interfacing With High Level Programming Language
Interfacing With High Level Programming Language
.AIR UNIVERSITY ISLAMABAD
 
Code Converters & Parity Checker
Code Converters & Parity CheckerCode Converters & Parity Checker
Code Converters & Parity Checker
.AIR UNIVERSITY ISLAMABAD
 

More from .AIR UNIVERSITY ISLAMABAD (6)

Risk Assessment
Risk AssessmentRisk Assessment
Risk Assessment
 
Mission ,Vision statement, and strategies of Unicef
Mission ,Vision statement, and strategies of UnicefMission ,Vision statement, and strategies of Unicef
Mission ,Vision statement, and strategies of Unicef
 
Pipelining & All Hazards Solution
Pipelining  & All Hazards SolutionPipelining  & All Hazards Solution
Pipelining & All Hazards Solution
 
Project Management System
Project Management SystemProject Management System
Project Management System
 
Interfacing With High Level Programming Language
Interfacing With High Level Programming Language Interfacing With High Level Programming Language
Interfacing With High Level Programming Language
 
Code Converters & Parity Checker
Code Converters & Parity CheckerCode Converters & Parity Checker
Code Converters & Parity Checker
 

Recently uploaded

Fundamentals of Electric Drives and its applications.pptx
Fundamentals of Electric Drives and its applications.pptxFundamentals of Electric Drives and its applications.pptx
Fundamentals of Electric Drives and its applications.pptx
manasideore6
 
CME397 Surface Engineering- Professional Elective
CME397 Surface Engineering- Professional ElectiveCME397 Surface Engineering- Professional Elective
CME397 Surface Engineering- Professional Elective
karthi keyan
 
Student information management system project report ii.pdf
Student information management system project report ii.pdfStudent information management system project report ii.pdf
Student information management system project report ii.pdf
Kamal Acharya
 
DESIGN A COTTON SEED SEPARATION MACHINE.docx
DESIGN A COTTON SEED SEPARATION MACHINE.docxDESIGN A COTTON SEED SEPARATION MACHINE.docx
DESIGN A COTTON SEED SEPARATION MACHINE.docx
FluxPrime1
 
Planning Of Procurement o different goods and services
Planning Of Procurement o different goods and servicesPlanning Of Procurement o different goods and services
Planning Of Procurement o different goods and services
JoytuBarua2
 
Basic Industrial Engineering terms for apparel
Basic Industrial Engineering terms for apparelBasic Industrial Engineering terms for apparel
Basic Industrial Engineering terms for apparel
top1002
 
Top 10 Oil and Gas Projects in Saudi Arabia 2024.pdf
Top 10 Oil and Gas Projects in Saudi Arabia 2024.pdfTop 10 Oil and Gas Projects in Saudi Arabia 2024.pdf
Top 10 Oil and Gas Projects in Saudi Arabia 2024.pdf
Teleport Manpower Consultant
 
HYDROPOWER - Hydroelectric power generation
HYDROPOWER - Hydroelectric power generationHYDROPOWER - Hydroelectric power generation
HYDROPOWER - Hydroelectric power generation
Robbie Edward Sayers
 
Unbalanced Three Phase Systems and circuits.pptx
Unbalanced Three Phase Systems and circuits.pptxUnbalanced Three Phase Systems and circuits.pptx
Unbalanced Three Phase Systems and circuits.pptx
ChristineTorrepenida1
 
Forklift Classes Overview by Intella Parts
Forklift Classes Overview by Intella PartsForklift Classes Overview by Intella Parts
Forklift Classes Overview by Intella Parts
Intella Parts
 
Nuclear Power Economics and Structuring 2024
Nuclear Power Economics and Structuring 2024Nuclear Power Economics and Structuring 2024
Nuclear Power Economics and Structuring 2024
Massimo Talia
 
Water Industry Process Automation and Control Monthly - May 2024.pdf
Water Industry Process Automation and Control Monthly - May 2024.pdfWater Industry Process Automation and Control Monthly - May 2024.pdf
Water Industry Process Automation and Control Monthly - May 2024.pdf
Water Industry Process Automation & Control
 
DfMAy 2024 - key insights and contributions
DfMAy 2024 - key insights and contributionsDfMAy 2024 - key insights and contributions
DfMAy 2024 - key insights and contributions
gestioneergodomus
 
14 Template Contractual Notice - EOT Application
14 Template Contractual Notice - EOT Application14 Template Contractual Notice - EOT Application
14 Template Contractual Notice - EOT Application
SyedAbiiAzazi1
 
Gen AI Study Jams _ For the GDSC Leads in India.pdf
Gen AI Study Jams _ For the GDSC Leads in India.pdfGen AI Study Jams _ For the GDSC Leads in India.pdf
Gen AI Study Jams _ For the GDSC Leads in India.pdf
gdsczhcet
 
block diagram and signal flow graph representation
block diagram and signal flow graph representationblock diagram and signal flow graph representation
block diagram and signal flow graph representation
Divya Somashekar
 
Hybrid optimization of pumped hydro system and solar- Engr. Abdul-Azeez.pdf
Hybrid optimization of pumped hydro system and solar- Engr. Abdul-Azeez.pdfHybrid optimization of pumped hydro system and solar- Engr. Abdul-Azeez.pdf
Hybrid optimization of pumped hydro system and solar- Engr. Abdul-Azeez.pdf
fxintegritypublishin
 
Design and Analysis of Algorithms-DP,Backtracking,Graphs,B&B
Design and Analysis of Algorithms-DP,Backtracking,Graphs,B&BDesign and Analysis of Algorithms-DP,Backtracking,Graphs,B&B
Design and Analysis of Algorithms-DP,Backtracking,Graphs,B&B
Sreedhar Chowdam
 
Cosmetic shop management system project report.pdf
Cosmetic shop management system project report.pdfCosmetic shop management system project report.pdf
Cosmetic shop management system project report.pdf
Kamal Acharya
 
Investor-Presentation-Q1FY2024 investor presentation document.pptx
Investor-Presentation-Q1FY2024 investor presentation document.pptxInvestor-Presentation-Q1FY2024 investor presentation document.pptx
Investor-Presentation-Q1FY2024 investor presentation document.pptx
AmarGB2
 

Recently uploaded (20)

Fundamentals of Electric Drives and its applications.pptx
Fundamentals of Electric Drives and its applications.pptxFundamentals of Electric Drives and its applications.pptx
Fundamentals of Electric Drives and its applications.pptx
 
CME397 Surface Engineering- Professional Elective
CME397 Surface Engineering- Professional ElectiveCME397 Surface Engineering- Professional Elective
CME397 Surface Engineering- Professional Elective
 
Student information management system project report ii.pdf
Student information management system project report ii.pdfStudent information management system project report ii.pdf
Student information management system project report ii.pdf
 
DESIGN A COTTON SEED SEPARATION MACHINE.docx
DESIGN A COTTON SEED SEPARATION MACHINE.docxDESIGN A COTTON SEED SEPARATION MACHINE.docx
DESIGN A COTTON SEED SEPARATION MACHINE.docx
 
Planning Of Procurement o different goods and services
Planning Of Procurement o different goods and servicesPlanning Of Procurement o different goods and services
Planning Of Procurement o different goods and services
 
Basic Industrial Engineering terms for apparel
Basic Industrial Engineering terms for apparelBasic Industrial Engineering terms for apparel
Basic Industrial Engineering terms for apparel
 
Top 10 Oil and Gas Projects in Saudi Arabia 2024.pdf
Top 10 Oil and Gas Projects in Saudi Arabia 2024.pdfTop 10 Oil and Gas Projects in Saudi Arabia 2024.pdf
Top 10 Oil and Gas Projects in Saudi Arabia 2024.pdf
 
HYDROPOWER - Hydroelectric power generation
HYDROPOWER - Hydroelectric power generationHYDROPOWER - Hydroelectric power generation
HYDROPOWER - Hydroelectric power generation
 
Unbalanced Three Phase Systems and circuits.pptx
Unbalanced Three Phase Systems and circuits.pptxUnbalanced Three Phase Systems and circuits.pptx
Unbalanced Three Phase Systems and circuits.pptx
 
Forklift Classes Overview by Intella Parts
Forklift Classes Overview by Intella PartsForklift Classes Overview by Intella Parts
Forklift Classes Overview by Intella Parts
 
Nuclear Power Economics and Structuring 2024
Nuclear Power Economics and Structuring 2024Nuclear Power Economics and Structuring 2024
Nuclear Power Economics and Structuring 2024
 
Water Industry Process Automation and Control Monthly - May 2024.pdf
Water Industry Process Automation and Control Monthly - May 2024.pdfWater Industry Process Automation and Control Monthly - May 2024.pdf
Water Industry Process Automation and Control Monthly - May 2024.pdf
 
DfMAy 2024 - key insights and contributions
DfMAy 2024 - key insights and contributionsDfMAy 2024 - key insights and contributions
DfMAy 2024 - key insights and contributions
 
14 Template Contractual Notice - EOT Application
14 Template Contractual Notice - EOT Application14 Template Contractual Notice - EOT Application
14 Template Contractual Notice - EOT Application
 
Gen AI Study Jams _ For the GDSC Leads in India.pdf
Gen AI Study Jams _ For the GDSC Leads in India.pdfGen AI Study Jams _ For the GDSC Leads in India.pdf
Gen AI Study Jams _ For the GDSC Leads in India.pdf
 
block diagram and signal flow graph representation
block diagram and signal flow graph representationblock diagram and signal flow graph representation
block diagram and signal flow graph representation
 
Hybrid optimization of pumped hydro system and solar- Engr. Abdul-Azeez.pdf
Hybrid optimization of pumped hydro system and solar- Engr. Abdul-Azeez.pdfHybrid optimization of pumped hydro system and solar- Engr. Abdul-Azeez.pdf
Hybrid optimization of pumped hydro system and solar- Engr. Abdul-Azeez.pdf
 
Design and Analysis of Algorithms-DP,Backtracking,Graphs,B&B
Design and Analysis of Algorithms-DP,Backtracking,Graphs,B&BDesign and Analysis of Algorithms-DP,Backtracking,Graphs,B&B
Design and Analysis of Algorithms-DP,Backtracking,Graphs,B&B
 
Cosmetic shop management system project report.pdf
Cosmetic shop management system project report.pdfCosmetic shop management system project report.pdf
Cosmetic shop management system project report.pdf
 
Investor-Presentation-Q1FY2024 investor presentation document.pptx
Investor-Presentation-Q1FY2024 investor presentation document.pptxInvestor-Presentation-Q1FY2024 investor presentation document.pptx
Investor-Presentation-Q1FY2024 investor presentation document.pptx
 

Dining philosopher

  • 1.
  • 2. Group members: ROLL NO: ROLL NO: ROLL NO: ROLL NO: ROLL NO: Group No 02 University of Azad Jammu & Kashmir Neelum Campus BSCS V Semester, 2014-18 Operating System Topic: Dining Philosophers Presented By: Mansoor Bashir
  • 3. Dining Philosopher’s Problem • Philosophers eat/think • Eating needs two forks • Pick one fork at a time
  • 4. Dining Philosophers Problem Five philosophers who spend their lives just thinking and eating. Only five chopsticks are available to the philosophers
  • 5. Dining Philosophers Problem Each philosopher thinks. When he becomes hungry, he sits down and picks up the two chopsticks that are closest to him and eats. After a philosopher finishes eating, he puts down the chopsticks and starts to think.
  • 7. Dining-Philosophers Problem Shared data : semaphore chopstick[5]; // Initialized to 1
  • 8. Dining-Philosophers Problem Philosopher i do { wait(chopstick[i]) wait(chopstick[(i+1)% 5]) eat signal(chopstick[i]); signal(chopstick[(i+1)% 5]) think } while (1);
  • 9. Possibility of Deadlock If all philosophers become hungry at the same time and pick up their left chopstick, a deadlock occurs.
  • 10. 17 December 2018 Possible Solutions  Allow at most four philosophers to be sitting simultaneously at the table.  Allow a philosopher to pick up his/her chopsticks only if both chopsticks are available (to do this she must pick them up in a critical section)
  • 11. 17 December 2018 Possible Solutions Use an asymmetric solution; that is, an odd philosopher picks up first her left chopstick, whereas an even philosopher picks up her right chopstick and then her left chopstick.
  • 12. 17 December 2018 Possibility of Starvation  Two philosophers who are fast eaters and fast thinkers, and lock the chopsticks before others every time.
  • 13. 17 December 2018 Critical Regions A critical region is a section of code that is always executed under mutual exclusion.
  • 14. 17 December 2018 Critical Regions  They consist of two parts: 1.Variables that must be accessed under mutual exclusion. 2.A new language statement that identifies a critical region in which the variables are accessed.
  • 16. Types of Semaphores  Counting semaphore – integer value can range over an unrestricted integer domain.  Binary semaphore – integer value cannot be > 1; can be simpler to implement.
  • 17. Implementing a Counting Semaphore  Data structures binary-semaphore S1, S2; int C;  Initialization S1 = 1 S2 = 0 C = initial value of semaphore S
  • 18. wait(S1); C--; if (C < 0) { signal(S1); wait(S2); } signal(S1); Implementing a Counting Semaphore wait(S):
  • 19. wait(S1); C++; if (C <= 0) signal(S2); else signal(S1); Implementing a Counting Semaphore signal(S):
  • 20. i. Deterministic algorithms ii. Randomized algorithm Algorithms Two Algorithm for dining Philosophers:
  • 21. Two goals to achieve in solving the problem: Deadlock free -- if at any time there is a hungry philosopher, then eventually some philosopher will eat. Lockout free -- every hungry philosopher eventually gets to eat. The configuration of philosophers and sticks for the case of n = 5 is illustrated below:
  • 22. 1. Deterministic algorithms: As is proven in D. Lehman and M. O. Rabin's paper in 1981, no fully distributed and symmetric deterministic algorithm for dining philosophers is possible. We can prove it using the following example by introducing the role of an adversary. There can be an evil adversary, who contrives to produce deadlock. For example, the adversary can come up with the following "clever" strategy:  All n philosophers become hungry at the same moment
  • 23.  They each pick up their left fork simultaneously  because of the symmetry and the fact that each philosopher's behavior is strictly deterministic, they have no choice but to put down their sticks and try again later still precisely at the same time. By repeating this cycle constantly, the adversary will be able to bring deadlock into this problem, thus makes any deterministic algorithms fail to work. Continue….
  • 25.  Fork Available[i] is a Boolean variable for each Pi - Pi+1 pair, which indicates whether the fork between them is available.  The subtractions and additions are to be interpreted modulo n We toss a coin when the hungry philosopher decides whether to pick up the left fork or the right one first. This randomization prevents any evil adversary's scheme. We can show that the algorithm is deadlock free. Continue….
  • 26. The proof is based on that the coin tosses made by philosophers are independent random events. Thus, even if the adversary scheduler tries to bring on deadlock, a combination of tosses will finally arise that enables some philosopher to obtain two sticks. As the index number (0,1,...i) attached to a philosopher is for naming only, the algorithm is totally symmetric. Continue….
  • 27. However, this algorithm is not lockout free. There can exist a very greedy philosopher Pi, and he tries to prevent his neighbor from eating by always beating him in the race of picking up the stick. Therefore, we need some more parameters to improve this algorithm. We can add two variables for each pair of philosophers, one lets Pi to inform Pi+1 of his desire to eat, and vice versa. The other shows which of the two eats last. In this way, we can achieve both the deadlock free and lockout free Continue….
  • 28. 17 December 2018 Monitor Dining Philosophers Example monitor dp { enum {thinking, hungry, eating} state[5]; condition self[5]; void pickup(int i) // Following slides void putdown(int i) // Following slides void test(int i) // Following slides void init() { for (int i = 0; i < 5; i++) state[i] = thinking; } }
  • 29. 17 December 2018 Dining Philosophers void pickup(int i) { state[i] = hungry; test(i); if (state[i] != eating) self[i].wait(); }
  • 30. 17 December 2018 void putdown(int i) { state[i] = thinking; // test left and right // neighbors test((i+4) % 5); test((i+1) % 5); } Dining Philosophers
  • 31. 17 December 2018 void test(int i) { if ((state[(i+4)%5]!= eating) && (state[i] == hungry) && (state[(i+1)%5]!= eating)) { state[i] = eating; self[i].signal(); } } Dining Philosophers