#include <stdio.h>
#include <semaphore.h>
#include <stdlib.h>
#include <pthread.h>
#include <unistd.h>
sem_t chopsticks[5];//chopsticks
void *PhilosopherEating(void *arg){
int index = *((int *)arg);
printf("%d\n",index);
int first=0;
int second=0;
int bOdd = index%2;
if(bOdd ==1){
first = index -1;
second = index%5;
}else{
first = index;
second = index -1;
}
while (1) {
sem_wait(&chopsticks[first]);
sem_wait(&chopsticks[second]);
//eating
printf("index :%d ,first:%d ,second:%d eating\n",index,first,second);
sem_post(&chopsticks[second]);
sem_post(&chopsticks[first]);
//think
sleep(1);
}
// pthread_exit(NULL);
}
int main()
{
printf("Hello World!\n");
int i=0;
pthread_t thread[5];
int index[5]={1,2,3,4,5};
for(i = 0 ; i <5 ; i++){
sem_init(&chopsticks[i],0,1);
}
for(i = 0 ; i < 5 ; i++){
pthread_create(&thread[i],NULL,PhilosopherEating,&index[i]);
}
for(i = 0 ; i < 5 ; i++){
pthread_join(&thread[i],NULL);
}
printf("Hello World!\n");
return 0;
}
信号量-哲学家进餐问题
最新推荐文章于 2025-12-01 20:43:59 发布
本文介绍了一个使用C语言实现的哲学家就餐问题,通过信号量sem_tchopsticks控制五个哲学家轮流使用两根筷子进行思考和进食。每个哲学家根据编号轮流获取相邻的筷子,展示了并发控制和互斥资源的原理。
390

被折叠的 条评论
为什么被折叠?



