#include <stdlib.h>
#include <stdio.h>
#include <unistd.h>
#include <semaphore.h>
#include <pthread.h>
#define PHILOSOPHER 5
sem_t chopstick[PHILOSOPHER];
sem_t mutex;
void *pro(void *arg)
{
int num;
num=*(int *)arg;
while(1)
{
sem_wait(&mutex);
sem_wait(&chopstick[num]);
sem_wait(&chopstick[(num+1)%PHILOSOPHER]);
printf("philosopher %d eat \n",num);
sem_post(&chopstick[(num+1)%PHILOSOPHER]);
sem_post(&chopstick[num]);
sem_post(&mutex);
sleep(3);
}
}
int main()
{
pthread_t philosopher_id[PHILOSOPHER];
int num=0;
int arg[PHILOSOPHER];
for(int i=0;i<PHILOSOPHER;i++)
{
sem_init(&chopstick[i],0,1);
arg[i]=i;
}
sem_init(&mutex,0,1);
for(int i=0;i<PHILOSOPHER;i++)
{
int thread=pthread_create(&philosopher_id[i],NULL,pro,(void *)&arg[i]);
if(thread!=0)
{
printf("进程创建失败!");
exit(1);
}
}
for(int i=0;i<PHILOSOPHER;i++)
{
pthread_join(philosopher_id[i],NULL);
}
return 0;
}
哲学家算法
最新推荐文章于 2022-09-02 11:29:43 发布