信号量解决:
伪代码:
semaphore chopstick[5] = {1,1,1,1,1};
semaphore room = 4;//房间4人
void philosophere(int i)
{
while (true)
{
think();
wait(room);
wait(chopsticks[i]);//获取左手边筷子
wait(chopsticks[(i+1)%5]);//获取右手边筷子
eat();
signal(chopsticks[(i+1)%5]);
signal(chopsticks[i]);
signal(room);
}
}
void main()
{
parbegin(philosopher0,philosopher1,philosopher2,philosopher3,philosopher4);
}
linux下c语言 实现:
#include<semaphore.h>
#include<stdio.h>
#include<stdlib.h>
#include<pthread.h>
#include<unistd.h>
#include<errno.h>
sem_t room;
sem_t chopsticks[5];
void *philosopher(void *arg);
int main()
{
sem_init(&room,0,4);
int i = 0;
int err;
void *tret;
pthread_t tid[5];
for (i = 0;i < 5;i++)
{
sem_init(&chopsticks[i],0,1);
}
for (i = 0;i < 5;i++)
{
err = pthread_create(&tid[i],NULL,philosopher,(void *)i);
if (err != 0){
perror("fail to create\n");
return -1;
}
}
for (i = 0;i < 5;i++)
{
err = pthread_join(tid[i],&tret);
if (err != 0)
{
perror("fail to join");
return -1;
}
}
sem_destroy(&room);
for (i = 0;i < 5;i++)
{
err = sem_destroy(&chopsticks[i]);
// sem_destroy(&room);
if (err != 0)
{
perror("fail to destroy");
return -1;
}
}
return 0;
}
void *philosopher(void *arg)
{
int i = 0;
i = (int)arg;
while (1)
{
// sleep(5);
printf("philosopher is thinking\n");
sem_wait(&room);
sem_wait(&chopsticks[i]);
sem_wait(&chopsticks[(i+1)%5]);
printf("philosopher %d is eating\n",i+1);
sem_post(&chopsticks[(i+1)%5]);
sem_post(&chopsticks[i]);
sem_post(&room);
}
return (void *)i;
// printf("philosopher is thinking\n");
}