您的位置:首页 > 其它

哲学家就餐问题的一个解法

2012-05-26 21:35 232 查看
哲学家就餐问题的简单描述:

  五个哲学家围坐在一张圆桌周围,每个哲学家面前都有一盘通心粉。由于通心粉很滑,所以需要两把叉子才能夹住。相邻的两个盘子之间放有一把叉子。

#define N 5

#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

semaphore mutex = 1;

semaphore s
;

void philosopher(int i)

{

  while(TRUE){

  }

}

void take_forks(int i)

{

  down(&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(i)

{

  if(state[i] == HUNGRY && state[LEFT] !=EATING && state[RIGHT] != EATING){

    state[i] = EATING;

    up(&s[i]);

  }

}
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: