#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;
}
信号量-哲学家进餐问题
最新推荐文章于 2024-07-16 18:16:07 发布