[讨论]著名的哲学家就餐
供大家思考题目:5个哲学家围坐一张桌,5把叉子,5盘意大利面,面太滑只能用两个叉子吃。哲学家有两种状态吃饭eating, thinking.编一个程序不产生死锁(死机):
#define N 5
#define LEFT (i+n-1)%N
#define RIGHT (i+1)%N
#define THINKING 0
#define HUNGRY 1
#define EATING 2
typedof int semaphore;
int state[N];
semaphore mutex=1;
semaphore s[N];
void philosopher(i)
{
while(TRUE)
{
think();
take_forks(i);
eat();
put_forks(i);
}
}
void take_forks(i)
{
dowm(&mutex);
state[i]=HUNGRY;
test(i);
up(&mutex);
down(&s[i]);
}
void put_forks(i)
{
down(&mutex);
state[i]=THINKING;
test(LEFT);
test(RIGHT);
up(&mutex);
}
void test(int i)
{
if(state[i]==HUNGERY&&state[align=LEFT]!=EATING&&state[align=RIGHT]!=EATING)
{
state[i]=EATING;
up(&s[i]);
}
}
**code copyed from morden operating system
呵呵怎么样 , 迷糊了吧
我也迷糊