现代操作系统-5个哲学家就餐问题

//liux版本

#include <stdio.h>

#include <pthread.h>
#include <semaphore.h>


#define N 8
#define LEFT (i+(N-1))%N
#define RIGHT (i+1)%N


#define THINKING 0 //不吃
#define HUNGRY 1//准备吃
#define EATING 2//在吃

pthread_mutex_t mutex = PTHREAD_MUTEX_INITIALIZER;//哲学家状态转换锁
sem_t s[N];//哲学家信号量
int state[N];//哲学家状态
pthread_t thrd[N];//哲学家动作线程
int test(int i)
{
if (state[i] == HUNGRY && state[LEFT] != EATING && state[RIGHT] != EATING){
//左右2个人都不在吃,则自己吃
state[i] = EATING;
printf("philosopher %d eating...\n",i);
sem_post(&s[i]);
return 1;
}
return 0;
}
void think(int i)
{
//printf("philosopher %d thinking...\n",i);
sleep(2);
//printf("philosopher %d thinking...over\n",i);
}
void take_forks(int i)
{
pthread_mutex_lock(&mutex);
state[i] = HUNGRY;
//看左右其他2个人是否在吃,都不在吃的时候,此人可吃,否则阻塞
int eating = test(i);
pthread_mutex_unlock(&mutex);

//test内如果在吃则up semaphore,下面down semaphore会立即返回,否则阻塞
sem_wait(&s[i]);
//只要sem_wait返回,则此人必定在吃,原因如下:
//1、在吃的话,sem_wait立即返回
//2、不在吃阻塞后,等他的左右2人吃完后驱动此人吃,也会导致up semaphore
if (i%2 == 0 && i >=4){
sleep(3);
printf("philosopher %d eating(3)...over\n",i);
}
else{
sleep(2);
printf("philosopher %d eating(2)...over\n",i);
}

}


void put_forks(int i)
{
//某人吃完,放叉子
pthread_mutex_lock(&mutex);
state[i] = THINKING;
//驱动左右2个人去吃
test(LEFT);
test(RIGHT);
pthread_mutex_unlock(&mutex);
}
void* philosopher(void* arg)
{
int i = *(int*)(arg);
printf("thread %d run...\n",i);
while(1){
think(i);
take_forks(i);
put_forks(i);
}
return NULL;
}
main()
{
int i = 0;
for (i = 0; i < N; i++){
sem_init(&s[i], 0, 0); 
}
for (i = 0; i < N; i++){
pthread_create(&thrd[i],NULL,philosopher,&i);
}
for (i = 0; i < N; i++){
pthread_join(thrd[i], NULL);
}

for (i = 0; i < N; i++){
sem_destroy(&s[i]); 
}
return 0;
}

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值