ALL > Computer and Education > courses > university courses > undergraduate courses > Operating System > ZSTU-(2020-2021)-1 > student homework > >
homework7 Version 0
👤 Author: by 1730854984qqcom 2020-11-13 14:26:19
The philosopher's dining is a typical example. There are many ways to solve the problem, but if used in the wrong way, it will lead to deadlock phenomenon. For example, one of the wrong solutions is to ask all philosophers to pick up the left hand chopsticks. This would result in no philosopher being able to pick up the chopsticks on the right hand side, causing a deadlock.

Four necessary conditions:
1. Mutual exclusion. A philosopher has a chopstick to himself.
2. Hold and wait. One philosopher has the left hand chopsticks and applies for the right hand chopsticks, but the right hand chopsticks are in the possession of another philosopher.
3. No preemption. The philosopher's chopsticks cannot be grabbed.
4. Circular wait. Each philosopher waits for the philosopher on the right to put down his chopsticks.

To solve the deadlock problem in philosopher's dining, we can set two conditions:
1. They must pick up both left and right chopsticks at the same time.2. They are allowed to eat only if neither of their neighbors is eating.


#define LEFT (i + N - 1) % N // 左邻居
#define RIGHT (i + 1) % N // 右邻居
#define THINKING 0
#define HUNGRY 1
#define EATING 2
typedef int semaphore;
int state[N]; // 跟踪每个哲学家的状态
semaphore mutex = 1; // 临界区的互斥
semaphore s[N]; // 每个哲学家一个信号量



void philosopher(int i) {
while(TRUE) {
think();
take_two(i);
eat();
put_two(i);
}
}
void take_two(int i) {
down(&mutex);
state[i] = HUNGRY;
test(i);
up(&mutex);
down(&s[i]);
}
void put_two(i) {
down(&mutex);
state[i] = THINKING;
test(LEFT);
test(RIGHT);
up(&mutex);
}
void test(i) { // 尝试拿起两把筷子
if(state[i] == HUNGRY && state[LEFT] != EATING && state[RIGHT] !=EATING) {
state[i] = EATING;
up(&s[i]);
}
}

Please login to reply. Login

Reversion History

Loading...
No reversions found.