//为简化操作,进程用数组表示
#include<stdio.h>
#define n 5
int in=0;
int out=0;
int Readcount[n];
int chopstick[n];//筷子状态标志
void Getchopstick(int nextw)//拿起筷子函数。 nextw为哲学家标号
{
printf("第%d名哲学家肚子饿了,申请左边的筷子。\n",nextw);
if(chopstick[nextw-1]==0||chopstick[nextw-1]==nextw)
{
in=nextw-1;
chopstick[in]=nextw;
printf("申请成功!第%d名哲学家已经拿起左边一支编号为%d筷子,申请右边编号为%d的筷子。\n",nextw,in,(in+1)%n);
in=(in+1)%n;
Readcount[nextw-1]=Readcount[nextw-1]+1;
if(chopstick[in]==0||chopstick[in]==nextw)
{
chopstick[in]=nextw;
Readcount[nextw-1]=Readcount[nextw-1]+1;
printf("申请成功!第%d名哲学家再拿起右边一支编号为%d筷子,开开心心的吃饭啦!\n",nextw,in);
}
else printf("申请失败!第%d名哲学家只有一支筷子,只好干巴巴的盼着旁边的那位哲学家赶快吃完。\n",nextw);
}
else printf("申请失败!第%d名哲学家没有拿到筷子,只好干巴巴的等着旁边的那位哲学家赶快吃完。\n",nextw);
}
void Dropchopstick(int nextr)//放下筷子函数。
{
// nextr为放下筷子的哲学家的编号
if(Readcount[nextr-1]!=0)//判断筷子是否已经占用
{
if(Readcount[nextr-1]==2)
{
printf("该名哲学家吃饱啦!准备放下筷子。。\n");
chopstick[nextr-1]=0;
chopstick[nextr]=0;
printf("该名哲学家已经放下筷子。。\n");
}
else {
printf("该名哲学家只有一支筷子!又不能吃饭,只好准备放下筷子。。\n");
chopstick[nextr-1]=0;
printf("该名哲学家已经放下筷子。。\n");
}
}
else printf("该名哲学家没有筷子你还让他放下。。你好坏啊~\n");
}
int select()
{
int i,nextw,nextr;
printf("请输入编号:\n1---拿筷子过程\n2---放筷子过程\n3---退出\n");
scanf("%d",&i);
switch(i)
{
case 1:
printf("现在进行哲学家拿筷子过程,请输入要申请筷子的哲学家编号(1-5)。\n");
scanf("%d",&nextw);
if((nextw>0)&&(nextw<6))
{
Getchopstick(nextw);//拿筷子过程
}
else {printf("输入超出范围,请重新输入!");}
break;
case 2:printf("现在进行哲学家放筷子过程,请输入要放筷子的哲学家编号(1-5)。\n");
scanf("%d",&nextr);
if((nextr>0)&&(nextr<6))
{
Dropchopstick(nextr);//放筷子过程
}
else {printf("输入超出范围,请重新输入!\n");}
break;
case 3:return(0);
default:printf("输入超出范围,请重新输入.\n");
scanf("%d",&i);
}
return(1);
}
int main()//主函数操作
{
printf("哲学家就餐问题。\n规则:每个人只有申请到了左边的筷子才可以申请右边的筷子。\n");
for(int m=0;m<n;m++)
{
chopstick[m]=0;
}
for(int c=0;c<n;c++)
{
Readcount[c]=0;
}
int i;
printf("请输入编号:\n1---拿放筷子操作\n2---退出\n");
scanf("%d",&i);
while(i!=2)
{
select();
printf("\n");
printf("请输入编号:\n1---拿放筷子操作\n2---退出\n");
printf("\n");
scanf("%d",&i);
}
return(1);
}
- 1
- 2
前往页