The document summarizes the dining philosophers problem, which illustrates challenges in avoiding deadlock in concurrent systems. It describes the problem scenario where five philosophers sit at a table and must alternate between eating spaghetti and thinking, but can only eat when holding both forks to their left and right. If the philosophers simply pick up forks in order, a deadlock can occur where each is waiting for the other's fork and no progress is possible. The document outlines the problem statement and provides background on concurrency, synchronization, and deadlocks to explain the challenge in solving the dining philosophers problem.
This document discusses semaphores and their use in solving critical section problems. It defines semaphores, describes their wait and signal methods, and types including counting and binary semaphores. It then explains how semaphores can be used to solve classical synchronization problems like the bounded buffer, readers-writers, and dining philosophers problems. Examples of semaphore implementations are provided for each problem.
The Dining Philosopher Problem – The Dining Philosopher Problem states that K philosophers seated around a circular table with one chopstick between each pair of philosophers. There is one chopstick between each philosopher. A philosopher may eat if he can pick up the two chopsticks adjacent to him.
1) A semaphore consists of a counter, a waiting list, and wait() and signal() methods. Wait() decrements the counter and blocks if it becomes negative, while signal() increments the counter and resumes a blocked process if the counter becomes positive.
2) The dining philosophers problem is solved using semaphores to lock access to shared chopsticks, with one philosopher designated as a "weirdo" to avoid deadlock by acquiring locks in a different order.
3) The producer-consumer problem uses three semaphores - one to limit buffer size, one for empty slots, and one for locks - to coordinate producers adding to a bounded buffer
Dining philosopher problem operating system anushkashastri
Ìý
The document discusses the dining philosophers problem, a classic synchronization problem used to evaluate situations where multiple resources need to be allocated to multiple processes. It was originally formulated by Edsger Dijkstra in 1965 to illustrate challenges of avoiding deadlock. The problem involves 5 philosophers who share 5 chopsticks placed in the center of a table to eat. The problem is to ensure that no philosopher starves while waiting for resources. Semaphores are used as a solution where each chopstick is represented by a semaphore to ensure mutual exclusion and avoid deadlock.
The document discusses various scheduling algorithms used in operating systems including:
- First Come First Serve (FCFS) scheduling which services processes in the order of arrival but can lead to long waiting times.
- Shortest Job First (SJF) scheduling which prioritizes the shortest processes first to minimize waiting times. It can be preemptive or non-preemptive.
- Priority scheduling assigns priorities to processes and services the highest priority process first, which can potentially cause starvation of low priority processes.
- Round Robin scheduling allows equal CPU access to all processes by allowing each a small time quantum or slice before preempting to the next process.
The document discusses three classical synchronization problems: the dining philosophers problem, the readers-writers problem, and the bounded buffer problem. For each problem, it provides an overview of the problem structure, potential issues like deadlock, and example semaphore-based solutions to coordinate access to shared resources in a way that avoids those issues. It also notes some applications where each type of problem could arise, like processes sharing a limited number of resources.
A presentation on the Dining Philosopher's Problem, explaining the problem, issues while solving the problem and solutions to the problem. The presentation then takes the user through the Requirement Engineering for the problem via its 4 phases, including, Requirement Discovery, Analysis, Validation and Management. The presentation also includes Use Case Diagrams and Data Flow Diagrams.
The document discusses the theory of NP-completeness. It begins by defining the complexity classes P, NP, NP-hard, and NP-complete. It then explains the concepts of reduction and how none of the NP-complete problems can be solved in polynomial time deterministically. The document provides examples of NP-complete problems like satisfiability (SAT), vertex cover, and the traveling salesman problem. It shows how nondeterministic algorithms can solve these problems and how they can be transformed into SAT instances. Finally, it proves that SAT is the first NP-complete problem by showing it is in NP and NP-hard.
This document discusses semaphores, which are integer variables that coordinate access to shared resources. It describes counting semaphores, which allow multiple processes to access a critical section simultaneously up to a set limit, and binary semaphores, which only permit one process at a time. Key differences are that counting semaphores can have any integer value while binary semaphores are limited to 0 or 1, and counting semaphores allow multiple slots while binary semaphores provide strict mutual exclusion. Limitations of semaphores include potential priority inversion issues and deadlocks if not used properly.
The document discusses deadlocks in computer systems. It defines deadlock, presents examples, and describes four conditions required for deadlock to occur. Several methods for handling deadlocks are discussed, including prevention, avoidance, detection, and recovery. Prevention methods aim to ensure deadlocks never occur, while avoidance allows the system to dynamically prevent unsafe states. Detection identifies when the system is in a deadlocked state.
This document discusses different types of scheduling algorithms used by operating systems to determine which process or processes will run on the CPU. It describes preemptive and non-preemptive scheduling, and provides examples of common scheduling algorithms like first-come, first-served (FCFS), shortest job first (SJF), round robin, and priority-based scheduling. Formulas for calculating turnaround time and waiting time are also presented.
Load Balancing In Distributed ComputingRicha Singh
Ìý
Load Balancing In Distributed Computing
The goal of the load balancing algorithms is to maintain the load to each processing element such that all the processing elements become neither overloaded nor idle that means each processing element ideally has equal load at any moment of time during execution to obtain the maximum performance (minimum execution time) of the system
A brief introduction to Process synchronization in Operating Systems with classical examples and solutions using semaphores. A good starting tutorial for beginners.
Branch and Bound is a state space search algorithm that involves generating all children of a node before exploring any children. It uses lower bounds to prune parts of the search tree that cannot produce better solutions than what has already been found. The algorithm is demonstrated on problems like the 8-puzzle and Travelling Salesman Problem. For TSP, it works by reducing the cost matrix at each node to calculate lower bounds, and exploring the child with the lowest estimated total cost.
1) The document discusses different types of micro-operations including arithmetic, logic, shift, and register transfer micro-operations.
2) It provides examples of common arithmetic operations like addition, subtraction, increment, and decrement. It also describes logic operations like AND, OR, XOR, and complement.
3) Shift micro-operations include logical shifts, circular shifts, and arithmetic shifts which affect the serial input differently.
This document summarizes the Banker's Algorithm, which is used to determine if a set of pending processes can safely acquire resources or if they should wait due to limited resources. It outlines the key data structures used like Available, Max, Allocation, and Need matrices to track current resources. The Safety Algorithm is described to check if the system is in a safe state by finding a process that can terminate and release resources. The Resource-Request Algorithm simulates allocating resources to a process and checks if it leads to a safe state before actual allocation.
The First Come First Serve (FCFS) CPU scheduling algorithm processes jobs in the order that they arrive in the ready queue. Newly arrived processes are added to the tail of the FIFO queue. The first process in the queue is scheduled first and removed from the queue. This is the simplest scheduling algorithm to implement but can result in long average wait times for processes as later arriving processes may have to wait for all earlier processes to complete.
Deadlock occurs when two or more processes are waiting for resources held by each other in a circular chain, resulting in none of the processes making progress. There are four conditions required for deadlock: mutual exclusion, hold and wait, no preemption, and circular wait. Deadlock can be addressed through prevention, avoidance, detection, or recovery methods. Prevention aims to eliminate one of the four conditions, while avoidance techniques like the safe state model and Banker's Algorithm guarantee a safe allocation order to avoid circular waits.
This document discusses concurrency control algorithms for distributed database systems. It describes distributed two-phase locking (2PL), wound-wait, basic timestamp ordering, and distributed optimistic concurrency control algorithms. For distributed 2PL, transactions lock data items in a growing phase and release locks in a shrinking phase. Wound-wait prevents deadlocks by aborting younger transactions that wait on older ones. Basic timestamp ordering orders transactions based on their timestamps to ensure serializability. The distributed optimistic approach allows transactions to read and write freely until commit, when certification checks for conflicts. Maintaining consistency across distributed copies is important for concurrency control algorithms.
The document discusses time and space complexity analysis of algorithms. Time complexity measures the number of steps to solve a problem based on input size, with common orders being O(log n), O(n), O(n log n), O(n^2). Space complexity measures memory usage, which can be reused unlike time. Big O notation describes asymptotic growth rates to compare algorithm efficiencies, with constant O(1) being best and exponential O(c^n) being worst.
The document discusses process synchronization and solutions to the critical section problem. It introduces the producer-consumer problem as an example that requires synchronization. The critical section problem aims to ensure that only one process at a time can be executing shared code or accessing shared data. Peterson's algorithm provides a solution for two processes using shared variables. Hardware synchronization methods like mutex locks and semaphores provide atomic primitives to synchronize processes. Semaphores use wait() and signal() operations to control access to shared resources without busy waiting.
Reasoning is the process of deriving logical conclusions from facts or premises. There are several types of reasoning including deductive, inductive, abductive, analogical, and formal reasoning. Reasoning is a core component of artificial intelligence as AI systems must be able to reason about what they know to solve problems and draw new inferences. Formal logic provides the foundation for building reasoning systems through symbolic representations and inference rules.
This document provides an introduction to POSIX threads (Pthreads) programming. It discusses what threads are, how they differ from processes, and how Pthreads provide a standardized threading interface for UNIX systems. The key benefits of Pthreads for parallel programming are improved performance from overlapping CPU and I/O work and priority-based scheduling. Pthreads are well-suited for applications that can break work into independent tasks or respond to asynchronous events. The document outlines common threading models and emphasizes that programmers are responsible for synchronizing access to shared memory in multithreaded programs.
The document provides an overview of problem spaces and problem solving through searching techniques used in artificial intelligence. It defines a problem space as a set of states and connections between states to represent a problem. Search strategies for finding solutions include breadth-first search, depth-first search, and heuristic search. Real-world problems discussed that can be solved through searching include route finding, layout problems, task scheduling, and the water jug problem is presented as a toy problem example.
It consists of CPU scheduling algorithms, examples, scheduling problems, realtime scheduling algorithms and issues. Multiprocessing and multicore scheduling.
Artificial Intelligence: Introduction, Typical Applications. State Space Search: Depth Bounded
DFS, Depth First Iterative Deepening. Heuristic Search: Heuristic Functions, Best First Search,
Hill Climbing, Variable Neighborhood Descent, Beam Search, Tabu Search. Optimal Search: A
*
algorithm, Iterative Deepening A*
, Recursive Best First Search, Pruning the CLOSED and OPEN
Lists
This document provides an overview of ISO 27005, which provides guidelines for information security risk management. It discusses establishing the context for risk management, assessing risks, treating risks, and monitoring the risk management process on an ongoing basis. Key activities covered include risk identification, analysis, evaluation, and acceptance criteria. Qualitative and quantitative risk analysis methodologies are described. The goal is to take a systematic approach to identify security needs and risks in order to create an effective information security management system.
Mission ,Vision statement, and strategies of UNICEF
Strategic Plan ,Mission Statement,vision,and Goal of UNICEF
Resource Partners, Sponsorship
UNICEF World Warehouse, UNICEF Research Center, UNICEF High Level structure
Recruitment & Selection Process of UNICEF
UNICEF’S STRENGTHS AND WEAKNESSES
The document discusses the theory of NP-completeness. It begins by defining the complexity classes P, NP, NP-hard, and NP-complete. It then explains the concepts of reduction and how none of the NP-complete problems can be solved in polynomial time deterministically. The document provides examples of NP-complete problems like satisfiability (SAT), vertex cover, and the traveling salesman problem. It shows how nondeterministic algorithms can solve these problems and how they can be transformed into SAT instances. Finally, it proves that SAT is the first NP-complete problem by showing it is in NP and NP-hard.
This document discusses semaphores, which are integer variables that coordinate access to shared resources. It describes counting semaphores, which allow multiple processes to access a critical section simultaneously up to a set limit, and binary semaphores, which only permit one process at a time. Key differences are that counting semaphores can have any integer value while binary semaphores are limited to 0 or 1, and counting semaphores allow multiple slots while binary semaphores provide strict mutual exclusion. Limitations of semaphores include potential priority inversion issues and deadlocks if not used properly.
The document discusses deadlocks in computer systems. It defines deadlock, presents examples, and describes four conditions required for deadlock to occur. Several methods for handling deadlocks are discussed, including prevention, avoidance, detection, and recovery. Prevention methods aim to ensure deadlocks never occur, while avoidance allows the system to dynamically prevent unsafe states. Detection identifies when the system is in a deadlocked state.
This document discusses different types of scheduling algorithms used by operating systems to determine which process or processes will run on the CPU. It describes preemptive and non-preemptive scheduling, and provides examples of common scheduling algorithms like first-come, first-served (FCFS), shortest job first (SJF), round robin, and priority-based scheduling. Formulas for calculating turnaround time and waiting time are also presented.
Load Balancing In Distributed ComputingRicha Singh
Ìý
Load Balancing In Distributed Computing
The goal of the load balancing algorithms is to maintain the load to each processing element such that all the processing elements become neither overloaded nor idle that means each processing element ideally has equal load at any moment of time during execution to obtain the maximum performance (minimum execution time) of the system
A brief introduction to Process synchronization in Operating Systems with classical examples and solutions using semaphores. A good starting tutorial for beginners.
Branch and Bound is a state space search algorithm that involves generating all children of a node before exploring any children. It uses lower bounds to prune parts of the search tree that cannot produce better solutions than what has already been found. The algorithm is demonstrated on problems like the 8-puzzle and Travelling Salesman Problem. For TSP, it works by reducing the cost matrix at each node to calculate lower bounds, and exploring the child with the lowest estimated total cost.
1) The document discusses different types of micro-operations including arithmetic, logic, shift, and register transfer micro-operations.
2) It provides examples of common arithmetic operations like addition, subtraction, increment, and decrement. It also describes logic operations like AND, OR, XOR, and complement.
3) Shift micro-operations include logical shifts, circular shifts, and arithmetic shifts which affect the serial input differently.
This document summarizes the Banker's Algorithm, which is used to determine if a set of pending processes can safely acquire resources or if they should wait due to limited resources. It outlines the key data structures used like Available, Max, Allocation, and Need matrices to track current resources. The Safety Algorithm is described to check if the system is in a safe state by finding a process that can terminate and release resources. The Resource-Request Algorithm simulates allocating resources to a process and checks if it leads to a safe state before actual allocation.
The First Come First Serve (FCFS) CPU scheduling algorithm processes jobs in the order that they arrive in the ready queue. Newly arrived processes are added to the tail of the FIFO queue. The first process in the queue is scheduled first and removed from the queue. This is the simplest scheduling algorithm to implement but can result in long average wait times for processes as later arriving processes may have to wait for all earlier processes to complete.
Deadlock occurs when two or more processes are waiting for resources held by each other in a circular chain, resulting in none of the processes making progress. There are four conditions required for deadlock: mutual exclusion, hold and wait, no preemption, and circular wait. Deadlock can be addressed through prevention, avoidance, detection, or recovery methods. Prevention aims to eliminate one of the four conditions, while avoidance techniques like the safe state model and Banker's Algorithm guarantee a safe allocation order to avoid circular waits.
This document discusses concurrency control algorithms for distributed database systems. It describes distributed two-phase locking (2PL), wound-wait, basic timestamp ordering, and distributed optimistic concurrency control algorithms. For distributed 2PL, transactions lock data items in a growing phase and release locks in a shrinking phase. Wound-wait prevents deadlocks by aborting younger transactions that wait on older ones. Basic timestamp ordering orders transactions based on their timestamps to ensure serializability. The distributed optimistic approach allows transactions to read and write freely until commit, when certification checks for conflicts. Maintaining consistency across distributed copies is important for concurrency control algorithms.
The document discusses time and space complexity analysis of algorithms. Time complexity measures the number of steps to solve a problem based on input size, with common orders being O(log n), O(n), O(n log n), O(n^2). Space complexity measures memory usage, which can be reused unlike time. Big O notation describes asymptotic growth rates to compare algorithm efficiencies, with constant O(1) being best and exponential O(c^n) being worst.
The document discusses process synchronization and solutions to the critical section problem. It introduces the producer-consumer problem as an example that requires synchronization. The critical section problem aims to ensure that only one process at a time can be executing shared code or accessing shared data. Peterson's algorithm provides a solution for two processes using shared variables. Hardware synchronization methods like mutex locks and semaphores provide atomic primitives to synchronize processes. Semaphores use wait() and signal() operations to control access to shared resources without busy waiting.
Reasoning is the process of deriving logical conclusions from facts or premises. There are several types of reasoning including deductive, inductive, abductive, analogical, and formal reasoning. Reasoning is a core component of artificial intelligence as AI systems must be able to reason about what they know to solve problems and draw new inferences. Formal logic provides the foundation for building reasoning systems through symbolic representations and inference rules.
This document provides an introduction to POSIX threads (Pthreads) programming. It discusses what threads are, how they differ from processes, and how Pthreads provide a standardized threading interface for UNIX systems. The key benefits of Pthreads for parallel programming are improved performance from overlapping CPU and I/O work and priority-based scheduling. Pthreads are well-suited for applications that can break work into independent tasks or respond to asynchronous events. The document outlines common threading models and emphasizes that programmers are responsible for synchronizing access to shared memory in multithreaded programs.
The document provides an overview of problem spaces and problem solving through searching techniques used in artificial intelligence. It defines a problem space as a set of states and connections between states to represent a problem. Search strategies for finding solutions include breadth-first search, depth-first search, and heuristic search. Real-world problems discussed that can be solved through searching include route finding, layout problems, task scheduling, and the water jug problem is presented as a toy problem example.
It consists of CPU scheduling algorithms, examples, scheduling problems, realtime scheduling algorithms and issues. Multiprocessing and multicore scheduling.
Artificial Intelligence: Introduction, Typical Applications. State Space Search: Depth Bounded
DFS, Depth First Iterative Deepening. Heuristic Search: Heuristic Functions, Best First Search,
Hill Climbing, Variable Neighborhood Descent, Beam Search, Tabu Search. Optimal Search: A
*
algorithm, Iterative Deepening A*
, Recursive Best First Search, Pruning the CLOSED and OPEN
Lists
This document provides an overview of ISO 27005, which provides guidelines for information security risk management. It discusses establishing the context for risk management, assessing risks, treating risks, and monitoring the risk management process on an ongoing basis. Key activities covered include risk identification, analysis, evaluation, and acceptance criteria. Qualitative and quantitative risk analysis methodologies are described. The goal is to take a systematic approach to identify security needs and risks in order to create an effective information security management system.
Mission ,Vision statement, and strategies of UNICEF
Strategic Plan ,Mission Statement,vision,and Goal of UNICEF
Resource Partners, Sponsorship
UNICEF World Warehouse, UNICEF Research Center, UNICEF High Level structure
Recruitment & Selection Process of UNICEF
UNICEF’S STRENGTHS AND WEAKNESSES
The document discusses pipeline hazards including structural, data, and control hazards. It provides details on how each hazard can occur in a 5-stage pipeline and techniques to resolve them, including forwarding, stalling, and compiler scheduling. Data hazards are classified as RAW, WAW, and WAR. Control hazards from branches are reduced by computing the branch target and outcome earlier in the ID phase to minimize stalls.
The document describes a project management system developed in C# and Visual Studio 2015. The system allows users to register and login, and managers can add, view, update, and delete employee, client, and project records stored in a SQL Server database. Key features and functions include registering users, viewing and managing employee, client, project, and stage information, and storing data securely with role-based access levels. Diagrams show the user interface and database tables used to store registration, employee, client, project, and other core data.
Interfacing With High Level Programming Language
High Level Programming Language
Categories of programming languages
Processing a High-Level Language Program
Advantages of high-level languages
Interface-Based Programming
Interfaces in Object Oriented Programming Languages
Implementing an Interface
Mansoor Bashir presented on code converters and parity checkers. Code converters change coded information from one system to another, such as converting decimal to binary. Parity checkers add an extra parity bit to detect errors by making the total number of 1s either even or odd. Even parity generators add a 0 bit to make the total number of 1s even, while odd parity generators add a 1 to make the total odd. Parity checkers use logic gates to check if the received bits have the correct parity or indicate an error.
EXPLORE 6 EXCITING DOMAINS:
1. Machine Learning: Discover the world of AI and ML!
2. App Development: Build innovative mobile apps!
3. Competitive Programming: Enhance your coding skills!
4. Web Development: Create stunning web applications!
5. Blockchain: Uncover the power of decentralized tech!
6. Cloud Computing: Explore the world of cloud infrastructure!
Join us to unravel the unexplored, network with like-minded individuals, and dive into the world of tech!
Optimization of Cumulative Energy, Exergy Consumption and Environmental Life ...J. Agricultural Machinery
Ìý
Optimal use of resources, including energy, is one of the most important principles in modern and sustainable agricultural systems. Exergy analysis and life cycle assessment were used to study the efficient use of inputs, energy consumption reduction, and various environmental effects in the corn production system in Lorestan province, Iran. The required data were collected from farmers in Lorestan province using random sampling. The Cobb-Douglas equation and data envelopment analysis were utilized for modeling and optimizing cumulative energy and exergy consumption (CEnC and CExC) and devising strategies to mitigate the environmental impacts of corn production. The Cobb-Douglas equation results revealed that electricity, diesel fuel, and N-fertilizer were the major contributors to CExC in the corn production system. According to the Data Envelopment Analysis (DEA) results, the average efficiency of all farms in terms of CExC was 94.7% in the CCR model and 97.8% in the BCC model. Furthermore, the results indicated that there was excessive consumption of inputs, particularly potassium and phosphate fertilizers. By adopting more suitable methods based on DEA of efficient farmers, it was possible to save 6.47, 10.42, 7.40, 13.32, 31.29, 3.25, and 6.78% in the exergy consumption of diesel fuel, electricity, machinery, chemical fertilizers, biocides, seeds, and irrigation, respectively.
This presentation provides an in-depth analysis of structural quality control in the KRP 401600 section of the Copper Processing Plant-3 (MOF-3) in Uzbekistan. As a Structural QA/QC Inspector, I have identified critical welding defects, alignment issues, bolting problems, and joint fit-up concerns.
Key topics covered:
✔ Common Structural Defects – Welding porosity, misalignment, bolting errors, and more.
✔ Root Cause Analysis – Understanding why these defects occur.
✔ Corrective & Preventive Actions – Effective solutions to improve quality.
✔ Team Responsibilities – Roles of supervisors, welders, fitters, and QC inspectors.
✔ Inspection & Quality Control Enhancements – Advanced techniques for defect detection.
📌 Applicable Standards: GOST, KMK, SNK – Ensuring compliance with international quality benchmarks.
🚀 This presentation is a must-watch for:
✅ QA/QC Inspectors, Structural Engineers, Welding Inspectors, and Project Managers in the construction & oil & gas industries.
✅ Professionals looking to improve quality control processes in large-scale industrial projects.
📢 Download & share your thoughts! Let's discuss best practices for enhancing structural integrity in industrial projects.
Categories:
Engineering
Construction
Quality Control
Welding Inspection
Project Management
Tags:
#QAQC #StructuralInspection #WeldingDefects #BoltingIssues #ConstructionQuality #Engineering #GOSTStandards #WeldingInspection #QualityControl #ProjectManagement #MOF3 #CopperProcessing #StructuralEngineering #NDT #OilAndGas
How to Build a Maze Solving Robot Using ArduinoCircuitDigest
Ìý
Learn how to make an Arduino-powered robot that can navigate mazes on its own using IR sensors and "Hand on the wall" algorithm.
This step-by-step guide will show you how to build your own maze-solving robot using Arduino UNO, three IR sensors, and basic components that you can easily find in your local electronics shop.
Lecture -3 Cold water supply system.pptxrabiaatif2
Ìý
The presentation on Cold Water Supply explored the fundamental principles of water distribution in buildings. It covered sources of cold water, including municipal supply, wells, and rainwater harvesting. Key components such as storage tanks, pipes, valves, and pumps were discussed for efficient water delivery. Various distribution systems, including direct and indirect supply methods, were analyzed for residential and commercial applications. The presentation emphasized water quality, pressure regulation, and contamination prevention. Common issues like pipe corrosion, leaks, and pressure drops were addressed along with maintenance strategies. Diagrams and case studies illustrated system layouts and best practices for optimal performance.
Engineering at Lovely Professional University (LPU).pdfSona
Ìý
LPU’s engineering programs provide students with the skills and knowledge to excel in the rapidly evolving tech industry, ensuring a bright and successful future. With world-class infrastructure, top-tier placements, and global exposure, LPU stands as a premier destination for aspiring engineers.
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
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.
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):
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