What Is the Dining Philosophers Problem?
The philosopher dining problem is one of the classic synchronization problems raised by Dutch scholar Dijkstra.
Dining Philosophers
Right!
- The dining problem of philosophers is by Dutch scholars
- By Dutch scholars
- The philosopher dining problem describes five philosophers. Their lifestyle is to alternate thinking and eating. The philosophers share a round table, sitting on five chairs around it, and there are five bowls and five on the round table. A chopstick, usually a philosopher thinking, when he was hungry, he tried to take the left and right chopsticks closest to him, and he could only eat when he got two chopsticks. After the philosopher finished the meal, he dropped the left and right chopsticks and continued Thinking.
- Restrictions
- (1) A philosopher can only eat when he has two chopsticks.
- (2) If the chopsticks have been taken away by others, you must wait for others to finish eating the chopsticks.
- (3) Any philosopher will not put down the chopsticks he has received before he has finished eating with two chopsticks.
- (1) Destruction request retention conditions
- Do it with atomic thought. That is, only a philosopher who picks up two chopsticks can eat, otherwise, one chopstick will not be taken.
- Solution one: The activity of the first philosopher using the AND mechanism is described as:
- philosopher (int I)
- {
- while (true)
- {
- Thinking;
- swait (chopstick [(I + 1)]% 5, chopstick [I]);
- meal;
- Ssignal (chopstick [I], chopstick [(I + i)% 5]);
- }
- }
- Solution two: use record type
- When using the semaphore mechanism to solve the synchronization problem, it is often cumbersome. It uses object-oriented thinking to encapsulate resources and resource sharing operations, manages them with management procedures, and realizes the dining problem for philosophers. It is more convenient to use.
- The algorithm implementation is described as follows:
- 1) Establish the management process
- monitor PC
- {
- semaphore chopstick [5] = 11,1,1,1,1);
- X: condition; / * define condition variable * /
- void Get: (int T) / * Define the process of taking chopsticks * /
- {
- Tf chopstick [I] = 1 and chopstick [(i + 1)% 5] = 1 then
- get the chopstick [I] and chopstick [(i + 1)% 5];
- else X. wait; / * If left and right chopsticks are not available, wait * /
- )
- void Put (int i) / * Define the process of putting down the chopsticks * /
- {
- put: the chopstick [I] and chopstick
- (i + 1)% 5];
- Tf X. quene then X. signal; / * Wake the philosophers waiting for chopsticks * /
- )
- }
- 2) Use the tube
- Activity of the first philosopher:
- void philosopher (int I)
- {
- while (true)
- {
- Thinking
- get: (I);
- meal;
- put (I);
- }
}