#include<stdio.h>#include<semaphore.h>#include<stdlib.h>#include<pthread.h>#include<unistd.h>sem_t chopsticks[5];//chopsticksvoid*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]);//eatingprintf("index :%d ,first:%d ,second:%d eating\n",index,first,second);sem_post(&chopsticks[second]);sem_post(&chopsticks[first]);//thinksleep(1);}// pthread_exit(NULL);}intmain(){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");return0;}