我正在尝试实现经典餐饮哲学家问题的修改形式。
假设有 5 位哲学家坐在桌子上。桌子上有 3 个叉子和 3 个勺子。哲学家可以拿起桌子上的任何勺子或叉子。哲学家吃饭需要叉子和勺子。
我用一个过程来代表每个哲学家。我使用了两个命名信号量: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 编译程序。