用餐哲学家在C

时间:2018-05-14 03:51:01

标签: c linux dining-philosopher

在为班级使用管道时必须设计Dining Philosophers计划。在管道消息传递中遇到一些麻烦。到目前为止,这是我的代码:

#include <stdio.h>
#include <stdlib.h>
#include <semaphore.h>
#include <pthread.h>
#include <unistd.h>
#include <sys/types.h>
#include <sys/wait.h>

#define N 5
#define LEFT (i + 4) % N
#define RIGHT (i + 1) % N
#define THINKING 0
#define HUNGRY 1
#define EATING 2

sem_t spoon;
sem_t phil[N];
int state[N];
int philNum[N] = {0, 1, 2, 3, 4};
int fd[N][2];
pid_t pid, pids[N];
int i;
int num;

void philosopher(int i);
void test(int i);
void takeSpoon(int i);
void putSpoon(int i);

char buffer[100];

我很确定问题出在管道上。

int main()
{
   for(i = 0; i < N; i++)
   {
      pipe(fd[i]);
      pids[i] = fork();
      printf("i = %d\n", i);
      printf("pids[i] = %d\n", pids[i] );

      if(pids[i] == 0)
      {
         dup2(fd[i][1], 1);
         close(fd[i][0]);
         close(fd[i][1]);
         philosopher(i);
         exit(0);
      }

      else if(pids[i] > 0)
      {
         dup2(fd[i][0], 0);
         close(fd[i][0]);
         close(fd[i][1]);
      }
    }

    for(i = 0; i < N; i++)
    {
      waitpid(pids[i], NULL, 0);
    }
    return 0;
}


void philosopher(int i)
{
  while(1)
  {
    sleep(1);
    takeSpoon(i);
    sleep(2);
    putSpoon(i);
    sleep(1);
  }
}

试图找出通过管道实现发生消息传递的原因。

void takeSpoon(int i)
{
  sem_wait(&spoon);
  state[i] = HUNGRY;
  printf("Philosopher %d is hungry\n", i + 1);
  test(i);
  sem_post(&spoon);
  sem_wait(&phil[i]);
}

void putSpoon(int i)
{
  sem_wait(&spoon);
  state[i] = THINKING;
  printf("Philosopher %d puts downspoon %d and %d\n", i + 1, LEFT + 1, i + 1);
  printf("Philosopher %d thinks\n", i + 1);
  test(LEFT);
  test(RIGHT);
  sem_post(&spoon);
}

void test(int i)
{
  if(state[i] == HUNGRY && state[LEFT] != EATING && state[RIGHT] != EATING)
  {
    state[i] = EATING;
    printf("Philosopher %d takes spoon %d and %d \n",i + 1, LEFT + 1, i + 1);
    printf("Philosopher %d eats \n", i + 1);
    sem_post(&phil[i]);
  }
}

输出:

i = 0

i = 0

pids [i] = 282

pids [i] = 0

i = 1

i = 1

pids [i] = 283

pids [i] = 0

i = 2

i = 2

pids [i] = 284

pids [i] = 0

i = 3

i = 3

pids [i] = 285

pids [i] = 0

i = 4

i = 4

pids [i] = 286

pids [i] = 0

0 个答案:

没有答案