我正在尝试实现经典餐饮哲学家问题的改进形式。
假设桌上有5位哲学家。桌子上放着3把叉子和3把勺子。哲学家可以选择桌上的任何汤匙或叉子。哲学家需要叉子和勺子才能吃东西。
我正在用过程代表每个哲学家。我使用了两个名为semaphore的信号量:semf和semt分别代表叉子和勺子。
该过程没有同步化。证明这一点的一种简单方法是有两个哲学家,并提供一个汤匙和叉子。
代码如下:
#include <stdio.h>
#include <stdlib.h>
#include <sys/types.h>
#include <errno.h>
#include <semaphore.h>
#include <fcntl.h>
#define SEFORK "/eatingforksem"
#define SSPOON "/spoonsem"
int main()
{
int i;
pid_t pid;
unsigned int n;
unsigned int fvalue;
unsigned int svalue;
printf ("How many Philosophers are sitting on the table?\n");
printf ("Philosopher count: ");
scanf ("%u", &n);
printf ("Count of Eating Forks?\n");
printf ("Eating Fork Count: ");
scanf ("%u", &fvalue);
printf ("Count of Eating Spoons?\n");
printf ("Eating Spoon Count: ");
scanf ("%u", &svalue);
sem_t *semf = sem_open(SEFORK, O_CREAT, 0644, fvalue);
sem_t *sems = sem_open(SSPOON, O_CREAT, 0644, svalue);
printf ("semaphores initialized.\n\n");
for (i = 0; i < n; i++){
pid = fork ();
if (pid < 0) {
sem_unlink (SEFORK);
sem_unlink (SSPOON);
sem_close(semf);
sem_close(sems);
printf ("Fork error.\n");
}
else if (pid == 0)
break; /* child processes */
}
if (pid != 0){
while (pid = waitpid (-1, NULL, 0)){
if (errno == ECHILD)
break;
}
sem_unlink (SEFORK);
sem_unlink (SSPOON);
sem_close(semf);
sem_close(sems);
printf ("\nParent: All Philosphers have eaten.\n");
exit (0);
}
else{
sem_t *semf = sem_open(SEFORK, 0);
sem_t *sems = sem_open(SSPOON, 0);
printf(" Philosopher %d is thinking\n", i);
sleep (3);
printf(" Philosopher %d is hungry\n", i);
sleep (3);
sem_wait (semf);
printf(" Philosopher %d has picked a fork\n", i);
sleep (3);
sem_wait (sems);
printf(" Philosopher %d has picked a spoon and is eating\n", i);
sleep (3);
sem_post (semf);
printf(" Philosopher %d has put down the fork\n", i);
sem_post (sems);
printf(" Philosopher %d has put down the spoon and finished eating\n", i);
sleep (3);
exit (0);
}
return 0;
}
我正在使用带有标志-lpthread -lrt -pthread的gcc编译程序。