📄 dine.c
字号:
#include<sys/types.h>
#include<sys/ipc.h>
#include<sys/sem.h>
#include<stdio.h>
#include<pthread.h>
#include<stdlib.h>
#define N 5 //No. of philosophers
#define LEFT (N+id-1)%(N) //index of id's left neighbour
#define RIGHT (id+1)%(N) //index of id's right neighbour
#define THINKING 0 //Symbolic constant to indicate thinking
#define HUNGRY 1 //Symbolic constant to indicate hungry state i.e. trying to get the forks
#define EATING 2 //Symbolic constant to indicate eating state
int state[N]={0,0,0,0,0}; //Array to keep track of everyone's state, initially owner thinking
int semid[5]; //One semaphore per philosopher
pthread_mutex_t mutex;
struct sembuf op[2]={{0,-1,0},{0,1,0}};
void take_forks(int);
void put_forks(int);
void * philosopher(void *);
void up(int);
void down(int);
void test(int);
void think(int id)
{
printf("Philosopher %d Thinking\n",id+1);
sleep(1);
}
void eat(int id)
{
printf("Philosopher %d Eating \n",id+1);
sleep(1);
}
void down(int id)
{
if(semop(id,&op[0],1))
{
printf("semaphore down error\n");
exit(1);
}
}
void up(int id)
{
if(semop(id,&op[1],1))
{
printf("semaphore up error\n");
exit(1);
}
}
void * philosopher (void *i)
{
while(1)
{
int id=*(int *)i;
think(id);
take_forks(id);
eat(id);
put_forks(id);
}
}
void take_forks(int id)
{
printf("Philosopher %d trying to take forks\n",id+1);
if(pthread_mutex_lock(&mutex))
{
printf("mutex lock error\n");
exit(1);
}
state[id]=HUNGRY;
test(id);
if(pthread_mutex_unlock(&mutex))
{
printf("mutex unlock error\n");
exit(1);
}
down(semid[id]);
//sleep(3);
}
void test(int id)
{
if(state[id]==HUNGRY && state[LEFT]!=EATING && state[RIGHT]!=EATING)
{
state[id]=EATING;
up(semid[id]);
}
}
void put_forks(int id)
{
printf("Philosopher %d has put down forks\n",id+1);
if(pthread_mutex_lock(&mutex))
{
printf("mutex lock error\n");
exit(1);
}
state[id]=THINKING;
test(LEFT);
test(RIGHT);
if(pthread_mutex_unlock(&mutex))
{
printf("mutex unlock error\n");
exit(1);
}
//sleep(3);
}
main()
{
int k,i,key;
char a;
int phid[5]={0,1,2,3,4};
pthread_t ph[5];
pthread_mutex_init(&mutex,NULL);
for(i=0,a='A';i<5;i++,a++)
{
if((key=ftok("dine.c",a))<0)
{
printf("Error in generatin key for s[%d]\n",i+1);
exit(0);
}
semid[i]=semget(key,1,IPC_CREAT|0666); //create a semaphore for each philosopher
if(semid[i]<0)
{
printf("Error in creating semaphore s[%d]\n",i);
exit(0);
}
}
for(i=0;i<5;i++)
{
if(pthread_create(&ph[i],NULL,philosopher,(void *)&phid[i]))
{
printf("thread creation error\n");
exit(1);
}
printf("created the semaphore for philosopher %d with id %d\n",i+1,semid[i]);
}
for(i=0;i<5;i++)
{
pthread_join(ph[i],NULL);
}
}
⌨️ 快捷键说明
复制代码
Ctrl + C
搜索代码
Ctrl + F
全屏模式
F11
切换主题
Ctrl + Shift + D
显示快捷键
?
增大字号
Ctrl + =
减小字号
Ctrl + -